Running Shell Scripts
When you run a shell script, you have two primary options:
./script.sh
: This command runs the script in a new shell. Any variables set or changed in the script do not affect the parent shell.source script.sh
: This command runs the script in the current shell (no new shell is created). Any variables set or changed in the script affect the parent shell.
Variables: Local vs. Environment
- Local Scope Variable:
var=ali
defines a variable that is only available within the current shell or script. - Environment Variable:
export name=ali
sets an environment variable that is available to the current shell and any child processes or scripts.
Special Variables
$@
vs.$*
:$@
creates a collection of all the positional parameters, maintaining each parameter as a separate entity.$*
creates a single string containing all the positional parameters.$0
: This variable contains the name of the script or command being executed.$#
: This variable contains the number of positional parameters passed to the script.
Script Arguments
When executing a script with arguments like ./script.sh val1 val2
, val1
and val2
are passed as positional parameters $1
and $2
respectively.
Exit Status
exit 0
: Indicates successful execution.exit 1
: Indicates an error occurred.
Testing with test
if test 1 -lt 2
is equivalent toif [ 1 -lt 2 ]
: Both test if 1 is less than 2.
File Tests
-a FILE
: True if file exists.-b FILE
: True if file is a block special file.-c FILE
: True if file is a character special file.-d FILE
: True if file is a directory.-e FILE
: True if file exists.-f FILE
: True if file exists and is a regular file.-g FILE
: True if file has the set-group-id flag set.-h FILE
: True if file is a symbolic link.-L FILE
: True if file is a symbolic link.-k FILE
: True if file has its sticky bit set.-p FILE
: True if file is a named pipe.-r FILE
: True if file is readable by you.-s FILE
: True if file exists and is not empty.-S FILE
: True if file is a socket.-t FD
: True if file descriptor FD is opened on a terminal.-u FILE
: True if the file has the set-user-id flag set.-w FILE
: True if the file is writable by you.-x FILE
: True if the file is executable by you.-O FILE
: True if the file is effectively owned by you.-G FILE
: True if the file is effectively owned by your group.-N FILE
: True if the file has been modified since it was last read.
Arithmetic Tests
Use one of the following operators:
-eq
: Equal-ne
: Not equal-lt
: Less than-le
: Less than or equal-gt
: Greater than-ge
: Greater than or equal
Variable Testing
if [[ $var ]]
vs.if [ "$var" ]
: Both check if the variablevar
is set and not empty.
Command Substitution
Store the result of a command in a variable using:
var=$(id -u)
: Preferred modern syntax.var=\
id -u“: Older syntax using backticks.