Spaces and curly braces for variables in bash

1k views Asked by At

Is there a way to make ${VAR} expand as if it were quoted in double quotes?

That's not what I wanted to see:

% A="some spaces in there"
% touch ${A}
% ls -1
in
some
spaces
there

Sure, I can use typical notation like "$VAR". But that's cumbersome when using quotes within quoted text, etc. I wonder if there's a way of expanding ${...} notation that would treat ${...} as if it were "${...}" while not using doublequotes themselves?

2

There are 2 answers

1
Paul Rubel On

You can set the IFS variable to disregard spaces when the shell splits variables. This is also useful when taking in input that may contain spaces in loops.

$ cat /tmp/t.sh
IFS="$(printf '\n\t')"
A="some spaces in there"
touch ${A}
ls -l
$ /tmp/t.sh
some spaces in there

(If you have characters like * in your strings try a set -f to disable globbing (see help set) thanks @glenn jackman. But really, putting a * in a filename is asking for trouble!)

And the original:

$ cat /tmp/t.sh
#!/bin/bash
A="some spaces in there"
touch ${A}
ls -1
$ /tmp/t.sh 
in
some
spaces
there
$
0
l0b0 On

Not following accepted best practice (and learning how the shell really works) is very likely to bite you. Repeatedly. With zombie virus-infected fangs. Some things which can help:

  • You can use different quotes for different parts of a single parameter as long as the start and end quotes are next to each other:

    $ printf '%q\n' "foo 'bar' baz"'nuu "boo" zoo'
    foo\ \'bar\'\ baznuu\ \"boo\"\ zoo
    
  • You can set IFS in a subshell to avoid screwing up your entire script:

    $ a="some spaces in there"
    $ (IFS= && touch ${a})
    $ ls -1
    some spaces in there