bash
This demonstrates using the IFS
variable to split a comma-separated string and iterate over its elements in a for
loop.
IFS=',' string="apple,banana,cherry" for fruit in $string; do echo "Fruit: $fruit" done
bash internaldata manipulationsstring manipulation and expansionsIFS
(Internal Field Separator)
bash
This demonstrates the use of built-in Bash variables to access script information like return values, process ID, and arguments.
echo "Last program's return value: $?" echo "Script's PID: $$" echo "Number of arguments passed to script: $#" echo "All arguments passed to script: $@" echo "Script's arguments separated into different variables: $1 $2..."
bash internaldata manipulationspositional argumentsbuilt-in variables
bash
This demonstrates redirecting both standard output and standard error to a single log file in Bash.
python hello.py > "output-and-error.log" 2>&1 # redirect both output and errors to output-and-error.log # &1 means file descriptor 1 (stdout), so 2>&1 redirects stderr (2) to the current # destination of stdout (1), which has been redirected to output-and-error.log.
bash internalfile and stream operationsstream redirection and pipingcombined redirection
bash
This demonstrates various methods of redirecting stdout
and stderr
in Bash, including appending, discarding, and combining streams.
python hello.py > output.txt # stdout to (file) python hello.py >> output.txt # stdout to (file), append python hello.py 2> error.log # stderr to (file) python hello.py 2>&1 # stderr to stdout python hello.py 2>/dev/null # stderr to (null) python hello.py >output.txt 2>&1 # stdout and stderr to (file), equivalent to &> python hello.py &>/dev/null # stdout and stderr to (null) echo "$0: warning: too many users" >&2 # print diagnostic message to stderr
bash internalfile and stream operationsstream redirection and pipingstdout redirection
bash
This demonstrates basic array manipulation in Bash, including accessing elements, counting, slicing, and iterating.
array=(one two three four five six) # Print the first element: echo "${array[0]}" # => "one" # Print all elements: echo "${array[@]}" # => "one two three four five six" # Print the number of elements: echo "${#array[@]}" # => "6" # Print the number of characters in third element echo "${#array[2]}" # => "5" # Print 2 elements starting from fourth: echo "${array[@]:3:2}" # => "four five" # Print all elements each of them on new line. for item in "${array[@]}"; do echo "$item" done
bash internaldata manipulationsarray manipulationbasic array operations