Bash Scripting gist
basename find wc compgen -k compgen -b -z flag to redirect stderr: 2> to redirect stdoutput: > converting stderr to stdout: 2>&1 converting stdout to stderr: echo “hello” >&2 Add the nunber(File descriptor value) 1/2 depending on the deired output format after & for conversion. Silence standard ouput and error both: ./file.sh > /dev/null 2>&1
Heredoc Strings:
cat <<EOF
text
text
text
text
EOF
ssh -T ubuntu@ubuntumaschine <<EOF
ls
EOF
Redirect output of heredoc string to a file.
cat <<EOF > helloworld.txt
text
text
text
text
EOF
ssh into remote and redirect the content of schema.sql into /var/log
ssh -T ubuntu@ubuntumachine bash "<<EOF >/var/log
cat /home/bob/docker_files/backup/sql_files/schema.sql
EOF"
Use heredoc string to quesry sql in docker
sudo docker exec my_postgres_container bash -c "psql -U postgres -d employees << EOF
select * from employee;
EOF"
Editing a file using file descriptor name: Assign file descriptor number to the file
exec 8<> /the/concerned/file.txt
Read the poistional value that needs to be edited.
cat /the/concerned/file.txt
a -> position 0
b -> position 1
c -> position 2
add character d at position 3
read -n 3 <& 8
address fo file descriptor to be sent at 3 position. Redirect position we opened above
echo "d" >& 8
Close the file desciptor number relationship
exec 8>&-
count number of the in the file.
cat sample.txt | grep -o "the" | wc -l
setting prevents errors in a pipeline from being masked
#!/bin/bash
set -o pipefail
If command produces a non-zero exit status, the script will immediately halt the execution and will exit with a status code 1, signifying an error.
|| exit 1
Error code with error message:
cat "${logfile}" | grep "ERROR" | sort | uniq -c || { echo "Error encountered in pipe commands" >&2; exit 1; }