1. pushd & pop
pushd
command is used to save the current directory into a stack and move to a new directory.
popd
can be used to return back to the previous directory that is on top of the stack.
pushd
andpopd
work according to the “LIFO” (last in, first out) principle.
To know the stack of directories use dirs and to clear entire stack use dirs -c.
2. default values
# $FOO, or val if unset (or null)
# if FOO is unset
echo "${FOO:-val}" # output: val
echo "$FOO" # output:
# Set $FOO to val if unset (or null)
# if FOO is unset
echo "$FOO" # output:
echo "${FOO:=val}" # output: val
echo "$FOO" # output: val
# val if $FOO is set (and not null)
echo "$FOO" #output: 123
echo "${FOO:+val}" # output: val
# Show error message and exit if $FOO is unset (or null)
echo "$FOO" # output:
echo "${FOO:?how dare you}" # output: zsh: FOO: how dare you
3. Eval
The eval command is a built-in command. It takes a string as its argument and evaluate it, then run the command stored in the argument. It allows using the value of a variable as a variable.
Example 1:
command="ls -lrt"
# zsh: command not found: ls -lrt
$command
echo "execute the command in child process"
eval $command
Example 2:
var1="hello"
var2=var1
echo_var="echo"
eval $echo_var \${$var2}
# -> 1. eval echo $var1
# -> 2. echo $var1
Example 3:
#!/bin/bash
addition=0
for ((i=1;i<=$1;i++))
do
eval x$i=$i
addition=$(($addition+x$i))
done
command="echo 'The sum of first $1 numbers is:'"
eval $command $addition
4 parentheses
This sign is mainly used for numerical evaluation. It is a compound command.
( 10 > 5 ) && echo true || echo false
-> false
(( 10 > 5 )) && echo true || echo false
-> true
Look at the above snippet, single bracket ( ) gives error while double bracket (( )) successfully executes the command.