bash: passing paths with spaces as parameters?

我怕爱的太早我们不能终老 提交于 2019-12-03 10:15:14
#! /bin/bash

for fname in "$@"; do
  process-one-file-at-a-time "$fname"
done

Note the excessive use of quotes. It's all necessary.

Passing all the arguments to another program is even simpler:

process-all-together "$@"

The tricky case is when you want to split the arguments in half. That requires a lot more code in a simple POSIX shell. But maybe the Bash has some special features.

You want "$@", which has the special syntax of expanding $@ but preserving the white-space quoting of the caller (it does not create a single giant string with all the arguments in it). So someone can call your script like:

bash-script.sh AFile "Another File With Spaces"

Then in your script you can do things like:

for f in "$@"; do 
  echo "$f"; 
done

and get two lines of output (not 5).

Read the paragraph about the Special Parameter "@" here: http://www.gnu.org/s/bash/manual/bash.html#Special-Parameters

Bravo @Roland . Thans a lot for your solution

It has really worked!

I wrote a simple script function that opens a given path with nautilus.

And I've just nested a function with this "helper"-for-loop into the main function:

fmp ()  {

    fmp2() { 
        nautilus "$@"; 
    };

    for fname in "$@";
    do         
        fmp2 "$fname";         
    done; 
}

Now I'm able to make all my scripts work handling with paths just by turning them into nested functions wrapped by a function with this helper-for-loop.

"$var"

For example,

$ var='foo bar'

$ perl -E'say "<<$_>>" for @ARGV' $var
<<foo>>
<<bar>>

$ perl -E'say "<<$_>>" for @ARGV' "$var"
<<foo bar>>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!