# See: # - http://tldp.org/LDP/abs/html/string-manipulation.html#AEN5117 # - http://tldp.org/LDP/abs/html/internalvariables.html#POSPARAMREF # - http://tldp.org/LDP/abs/html/internalvariables.html#IFSREF # - http://tldp.org/LDP/abs/html/parameter-substitution.html#PARAMSUBREF # - cmdparser, http://codesnippets.joyent.com/posts/show/1697 export IFS=$' \t\n' # create a fake command line set -- "First one" "second" "third:one" "" "Fifth: :one" set -- "First one" "second" "third:"$'\n'"one" "" "Fifth: :one" echo $# # number of arguments printf "%s\n" "${@}" # all arguments printf "%s\n" "${1}" # first argument printf "%s\n" "${3}" # third argument printf "%s\n" "${5}" # last argument printf "%s\n" "${@:1}" # all arguments starting with the first printf "%s\n" "${@:2}" # all arguments starting with the second printf "%s\n" "${@:3}" # all arguments starting with the third printf "%s\n" "${@:(-$#):1}" # first argument printf "%s\n" "${@:$#:1}" # last argument printf "%s\n" "${!#}" # last argument printf "%s\n" "${@:1:1}" # first argument printf "%s\n" "${@:3:1}" # third argument printf "%s\n" "${@:5:1}" # fifth argument printf "%s\n" "${@:(-1):1}" # last argument printf "%s\n" "${@:(-2):1}" # second-to-last argument # process one positional parameter at a time without modifying $# or $@ for (( i=1; i <= $#; i++ )); do printf "%s\n" "${@:${i}:1}"; done echo $# # 5 # $# and $@ get modified for (( i=1; i <= $#; i++ )); do echo $i; printf "%s\n" "$1"; shift; done echo $# # 2 set -- "First one" "second" "third:"$'\n'"one" "" "Fifth: :one" # $# and $@ get modified while [[ $# -gt 0 ]]; do printf "%s\n" "$1"; shift; done echo $# # 0
Never been to CodeSnippets before?
Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)
Process positional parameters non-destructively in Bash (See related posts)
You need to create an account or log in to post comments to this site.
Related Posts
» cmdparser - parse command li... in regex shell osx mac bash command line option parse basic parameter parser switch argument flag getopts getopt posix gnu cmdparser
» cmdparser - parse command li... in regex shell osx mac bash command line option parse basic parameter parser switch argument flag getopts getopt posix gnu cmdparser builtin
» my_getopts_bash − parse co... in shell osx mac bash command line option glob parse update parameter parser ifs argument getopts getopt posix gnu cmdparser printf builtin declare extglob shopt extended eval
» ws - search the web from the... in shell osx mac search bash command line unix web cmdparser libidn
» Add Mac OS X menu bar items ... in shell osx mac bash command line unix open menu bar
» Tapping the Bash command lin... in shell osx mac bash command unix key history shortcut
Snippets (source code soon to be available) developed by Peter Cooper and powered by Ruby On Rails