Bash script advanced?
Wed Nov 26 2025 00:00:00 GMT+0000 (Coordinated Universal Time)
#!/bin/sh — comment that tells the shell which interpreter to use (“shebang”).
To source something in all new terminals:
nano ~/.bashrc`
# which shell I'm using
echo $SHELL
which bash
Then include your source command.
# create the script
nano myscript.sh
# enable execution permission — after this the file looks green
sudo chmod +x myscript.sh
# execute
./myscript.sh
Variables
# without space, assign variable; '' for var_name and "" for var_value
myname="vk"
echo $myname
# subshell
files=$(ls)
echo $files
# all caps → environmental var, all lower → local var
echo $USER
Math Functions
# evaluate expression
expr 10 + 30
expr 10 - 30
expr 10 / 30
expr 10 \* 30
if / else
[] is shorthand for the test command.
#if statements
if [ ]; then
else
fi
# comparison
! # not
-ne # not equal
-gt # greater than
# check file existence
if [ -f ~/myfile ]; then
echo "file exists"
else
echo "file does not exist"
fi
Install a package if not present:
#!/bin/bash
command=/usr/bin/htop
if [ -f $command ]; then
echo "$command is available, let's run it"
else
echo "$command is not available, let's install"
sudo apt update && sudo apt install -y htop
# && executes second command only if first succeeds
fi
$command
Exit Codes
Check whether the previous command was successful:
echo $? — success → 0, failure → non-zero.
$? outside an if block may show 0 because echo itself succeeded. Always check $? immediately after the command you want to test.
exit 1 — force exit code to 1; commands after exit will not run.
Useful special variables:
$0 — invoked script name
$1 — first argument to the script
$# — number of arguments
$? — exit status of the most recent command
Example:
if [ $? -eq 0 ]; then
echo "success"
exit 0
else
echo "failed: expected ${MATCHSTR} in ${OUTPUTSTRING} but instead found"
exit 1
fi