- Change the current directory/folder and store the previous folder/path for use by the popd command.
[user@server /usr/ports] $ pushd /etc
/etc /usr/ports
[user@server /etc] $ popd
/usr/ports
[user@server /usr/ports] $
- Quick way to retrieve the path of the bash script that is being executed.
#!/bin/bash
DIRECTORY=$(cd `dirname $0` && pwd)
echo $DIRECTORY
#!/bin/bash
echo $0
full_path=$(realpath $0)
echo $full_path
dir_path=$(dirname $full_path)
echo $dir_path
examples=$(dirname $dir_path )
echo $examples
data_dir="$examples/data"
echo "DATA: $data_dir"
./examples/shell/relative.sh
/home/gabor/work/code-maven.com/examples/shell/relative.sh
/home/gabor/work/code-maven.com/examples/shell
/home/gabor/work/code-maven.com/examples
DATA: /home/gabor/work/code-maven.com/examples/data
- tells the number of input arguments the script was passed.
if [ $# -eq 0 ]
then
echo "No arguments supplied"
fi
if [ -z "$1" ]
then
echo "No argument supplied"
fi
- In this example, it is not safe to use "$1" check, if it is not sure there is always an additional argument.
- Better reference the argument, if we are sure if such argument exists. In all other cases, check the count of arguments using $# and if it is greater than zero, reference the other arguments.
- POSIX compatible way of checking if a command exists or not.
if ! command -v COMMAND &> /dev/null
then
echo "COMMAND could not be found"
exit
fi
- command to retrieve all typed commands in bash terminal
- which looks for an executable file by searching for it in the directories in the PATH environmental variable.
- in GNU makefile
- $(shell command)
- The shell function accepts a single argument that is expanded (like all arguments) and passed to a subshell for execution. The standard output of the command is then read and returned as the value of the function. Sequences of newlines in the output are collapsed to a single space. Any trailing newline is deleted. The standard error is not returned, nor is any program exit status.
- count files recursively using find
- find -type f | wc -l