Bash: How to set positional parameters with whitespace preserved?

From FVue
Jump to: navigation, search

Problem

I want to remove the last positional parameters, but with possible whitespace preserved.

Solution

Using arrays

saved=( "$@" )                 # Copy positional parameters to array
unset saved[${#saved[@]}-1]    # Unset last parameter
set -- "${saved[@]}"           # Set new positional paramaters

Changing IFS

OIFS=$IFS; IFS=$'\012'
    #  NOTE: ${2+isset} is preferred because $2 gives error when
    #+       set -o nounset is defined.
set -- $(while [ "${2+isset}" ]; do echo "$1"; shift; done)
IFS=$OIFS  # Restore IFS

Journal

20061111

Google Groups | comp.unix.shell | bash: saving the positional parameters
Newsgroup topic with the array solution

Comments

blog comments powered by Disqus