Skip to content

Latest commit

 

History

History
124 lines (104 loc) · 2.31 KB

bash.adoc

File metadata and controls

124 lines (104 loc) · 2.31 KB

BASH BASH

paths

Script current dir

SCRIPT_FILEPATH=$( realpath -P ${BASH_SOURCE[0]} )
SCRIPT_DIRPATH=$( dirname "${SRCIPT_FILEPATH}" )
Note
In normal Bash script, $0 is the path to the script. However, when a script is sourced, such as . a.sh`, a.sh‘s $0 does not give a.sh while the caller’s name.

or if you want to deal with bash and zsh:

if [ -z ${BASH_SOURCE+x} ]; then SCRIPT_FILEPATH=${(%):-%N};
else SCRIPT_FILEPATH=${BASH_SOURCE[0]}; fi
SCRIPT_FILEPATH=$( realpath -P ${SCRIPT_FILEPATH} )
SCRIPT_DIRPATH=$( dirname "${SCRIPT_FILEPATH}" )

get basename

$ s=/the/path/foo.txt
$ echo ${s##*/}
foo.txt
$ s=${s##*/}
$ echo ${s%.txt}
foo
$ echo ${s%.*}
foo

loop over files

for f in *.jpg
do
  convert ./"$f" ./"${f%.jpg}.pdf"
done

Arguments

description

$0

script name as called.

$*

All parameters as single argument.

$@

All arguments, one argument per parameter.

$#

Nummber of parameters passés.

$?

Return code of last command.

$$

PID of shell running script.

$!

PID of last called processus in background.

Arrays

simple array
#!/bin/bash
array=( one two three ) # # (1)
for i in "${array[@]}" # # (2)
do
	echo $i # # (3)
done
  1. defines the array values

  2. loop over the values

  3. access element

outputs
one
two
three
multidimensional array
#!/bin/bash
declare -A casting
casting["the narator narrator"]="edward norton"
casting["tyler durden"]="brad pit"
for actor in "${casting[@]}" ; do # # (1)
echo "with $actor"
done
for role in "${!casting[@]}" ; do # # (2)
echo "${casting[$role]} is $role"
done
  1. ${casting[@]} loop over the values

  2. ${!casting[@]} loop over the keys

outputs
with brad pit
with edward norton
brad pit is tyler durden
edward norton is the narator narrator

Split long line

$> cmd | cmd | cmd | cmd # some comment
$> cmd \
  | cmd \
  `# some comment` \
  | cmd \
  | cmd