开发者

How to pass a parameter with space to an external program in a shell script?

开发者 https://www.devze.com 2023-03-24 23:14 出处:网络
a.sh #!/bin/bash description=`\"test message\"` # input parameter for contain a space binary=<external_prog> # simply display what passes to fl开发者_JAVA技巧ag --description

a.sh

#!/bin/bash
description=`"test message"` # input parameter for contain a space

binary=<external_prog> # simply display what passes to fl开发者_JAVA技巧ag --description

cmd="$binary --description=$description"

$cmd # run the external program

Question: message will miss, how to resolve it? Thanks!


#!/bin/bash
description="test message"
binary=program

cmd="$binary --description=\"$description\""

eval $cmd

or just run

$binary --description="$description"


The back-ticks in this are not wanted, unless you really have a program called 'test message' (with space in the name) that generates your desired output:

description=`"test message"` # input parameter for contain a space

The simplest way to achieve your requirement is to use double quotes around the (part of the) argument that needs to contain spaces:

description="test message"
binary=external_prog
$binary --description="$description"

You could equivalently write the last line as:

$binary "--description=$description"

This ensures that all the material in description is treated as a single argument, blanks and all.


If you're using bash or ksh or some shell with arrays, they are the safest way to contruct a command. In bash:

description="test message"
binary=some_prog
cmd=( "$binary" "--description=$description" )
"${cmd[@]}"

You can test it with something like this: say this is named "arg_echoer.sh"

#!/bin/sh
echo "$0"
i=0
for arg in "$@"; do
    let i="$i+1"
    echo "$i: $arg"
done

Then, if binary=./arg_echoer.sh, you get this output with "${cmd[@]}"

./arg_echoer.sh
1: --description=test message


The safe way is to use an array:

args=("--description=test message" "--foo=some other message")
args+=("--bar=even more")
cmd "${args[@]}"
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号