Pass hash-sign-starting-string parameter to a shel

2019-08-31 11:03发布

I try to pass a string containted between two # sign to a ksh script :

Will #> ./a.ksh #This is a string#

Will #>

Nothing is prompted, the execpeted output would be :

Will #> ./a.ksh #This is a string#
#This is a string#

Below the a.ksh script.

a.ksh

echo $1
echo "$1"
echo ${1}
echo "${1}"

I have tried to protect my $1 variable by any means I knew but I can't get anything starting with # to be displayed.

Those following don't work :

#> ./a.ksh #Hello
#> ./a.ksh #

But this do :

#> ./a.ksh Hello#

Any shell guru that could explain me why and how to get this to work as excpeted ?

I can escape those string using \#This String# or "#This String#" but I wonder why does # doesn't print by itself.

1条回答
劳资没心,怎么记你
2楼-- · 2019-08-31 11:39

# is interpreted as the start of a comment. All comments are ignored by the interpreter.

You have two options:

  1. Quote the string to make it a literal:

    ./a.ksh "#This is a string#"

  2. Have your script read input from the user instead of a parameter:

Here's an example:

#!/bin/ksh
echo "Enter your text:"
read -r input
echo "You entered: $input"

then run the program first and enter your data after:

$ ./a.ksh
Enter your text:
#This is a string#
You entered: #This is a string#
查看更多
登录 后发表回答