📝
Bash
On this page
Count the total number of lines that exist in whatever file the user enters:
sh
#!/bin/bashecho -n "Please enter a filename: "read filenamenlines=$(wc -l < $filename)echo "There are $nlines lines in $filename"
Convert mp4 files to mp3
bash
# From https://askubuntu.com/questions/837916/convert-mp4-to-mp3-using-shell-scriptvideos=$(find . -name '*.mp4')sounds=()sampleRate="48000"for video in $videos; dosound=${video%.mp4}.mp3if [ ! -f "$sound" ]; thenffmpeg -i "$video" -vn -acodec libmp3lame -ac 2 -qscale:a 4 -ar "$sampleRate" "$sound"sounds+=("$sound")fidoneecho "Converted ${#sounds[@]} vidoes"for i in "${sounds[*]}"; doecho -e "$i\n"done
Passing multiple arguments to a bash shell script
sh
script.sh arg1 arg2
sh
#!/bin/bashcd ..repo=$1cd $repobranch=${2:-'master'}git co $branchecho "start $repo($branch)"git pullyarnyarn start
Download remote config
sh
#!/bin/bashurl=${1:-'example.com'}endpoint=https://$url/config/config.jsonecho "⬇️ Download config from $endpoint"mkdir -p public/config/curl -o public/config/config-temp.json $endpoint
Replace values in json file
sh
#!/bin/bashDIRNAME=$(dirname $0)gsed -i -r 's;"label": ".*";"label": "'$(git branch --show-current --no-color)'";' ${DIRNAME}/../public/versions.json
gsedis an non-interactive stream editor.-i: edit files in place,-r: use extended regular expressions
Pass default value
Default value handling is done by parameter of the form: ${parameter:[-=?+]word} such as:
${parameter:-word}to use a default value${parameter:=word}to assign a default value (mutate original parameter)${parameter:?word}to display an errorif unset or null${parameter:+word}to use an alternate valueif parameter is set and not null
Special variables in Bash shell
| Special Variable | Description |
|---|---|
| $0 | The name of the bash script. |
| $1, $2...$n | The bash script arguments. |
| $$ | The process id of the current shell. |
| $# | The total number of arguments passed to the script. |
| $@ | The value of all the arguments passed to the script. |
| $? | The exit status of the last executed command. |
| $! | The process id of the last executed command. |
