Passing arguments to a command in Bash script with spaces Passing arguments to a command in Bash script with spaces unix unix

Passing arguments to a command in Bash script with spaces


See http://mywiki.wooledge.org/BashFAQ/050

TLDR

Put your args in an array and call your program as myutil "${arr[@]}"

#!/bin/bash -xvfile1="file with spaces 1"file2="file with spaces 2"echo "foo" > "$file1"echo "bar" > "$file2"arr=("$file1" "$file2")cat "${arr[@]}"

Output

file1="file with spaces 1"+ file1='file with spaces 1'file2="file with spaces 2"+ file2='file with spaces 2'echo "foo" > "$file1"+ echo fooecho "bar" > "$file2"+ echo bararr=("$file1" "$file2")+ arr=("$file1" "$file2")cat "${arr[@]}"+ cat 'file with spaces 1' 'file with spaces 2'foobar


This might be a good use-case for the generic "set" command, which sets the top-level shell parameters to a word list. That is, $1, $2, ... and so also $* and $@ get reset.

This gives you some of the advantages of arrays while also staying all-Posix-shell-compatible.

So:

set "arg with spaces" "another thing with spaces"cat "$@"


The most straightforward revision of your example shell script that will work correctly is:

#! /bin/shARG="/tmp/a b/1.txt"ARG2="/tmp/a b/2.txt"cat "$ARG" "$ARG2"

However, if you need to wrap up a whole bunch of arguments in one shell variable, you're up a creek; there is no portable, reliable way to do it. (Arrays are Bash-specific; the only portable options are set and eval, both of which are asking for grief.) I would consider a need for this as an indication that it was time to rewrite in a more powerful scripting language, e.g. Perl or Python.