Feature Group
bash internal (293)
bash
This demonstrates using a "here" document in Bash to create a Python script that interacts with stdout
, stderr
, and stdin
.
cat > hello.py << EOF #!/usr/bin/env python from __future__ import print_function import sys print("#stdout", file=sys.stdout) print("#stderr", file=sys.stderr) for line in sys.stdin: print(line, file=sys.stdout) EOF # Variables will be expanded if the first "EOF" is not quoted
bash internalfile and stream operationscontent operationshere-document (heredoc)
bash
This script redirects all output and errors from the python hello.py
command to /dev/null
, effectively suppressing any output or errors.
python hello.py > /dev/null 2>&1 # redirect all output and errors to the black hole, /dev/null, i.e., no output
bash internalfile and stream operationsstream redirection and pipingoutput suppression
bash
This demonstrates file and directory removal in Bash, including verbose and recursive deletion, and suggests using trash-cli
for safer file deletion.
rm -v output.out error.err output-and-error.log rm -r tempDir/ # recursively delete # You can install the `trash-cli` Python package to have `trash` # which puts files in the system trash and doesn't delete them directly # see https://pypi.org/project/trash-cli/ if you want to be careful
bash internalfile and stream operationsfile managementfile and directory deletion
bash
This demonstrates command-line option parsing using a while
loop and case
statement in Bash.
while [[ "$1" =~ ^- && ! "$1" == "--" ]]; do case $1 in -V | --version ) echo "$version" exit ;; -s | --string ) shift; string=$1 ;; -f | --flag ) flag=1 ;; esac; shift; done if [[ "$1" == '--' ]]; then shift; fi
bash internalflow controlloopswhile
loopcommand-line parsing
bash
This demonstrates special string slicing and substitution using parameter expansion.
name="John" echo "${name}" echo "${name/J/j}" #=> "john" (substitution) echo "${name:0:2}" #=> "Jo" (slicing) echo "${name::2}" #=> "Jo" (slicing) echo "${name::-1}" #=> "Joh" (slicing) echo "${name:(-1)}" #=> "n" (slicing from right) echo "${name:(-2):1}" #=> "h" (slicing from right) echo "${food:-Cake}" #=> $food or "Cake"
bash internaldata manipulationsstring manipulation and expansionsparameter expansionstring slicing
bash
This demonstrates extracting the base filename and directory path from a file path using parameter expansion.
src="/path/to/foo.cpp" base=${src##*/} #=> "foo.cpp" (basepath) dir=${src%$base} #=> "/path/to/" (dirpath)
bash internaldata manipulationsstring manipulation and expansionsparameter expansionpath manipulation