Bash:Single Quotes and Double Quotes and Exclamati

2019-07-20 02:51发布

I have a simple script named example:

#!/bin/sh
echo $'${1}'

Please note that the usage of $'' here is to convert \n into new line. ${1} is the first parameter passed to this shell script.

I want to pass a parameter to this script example and it prints the following:

#1. You're smart!
#2. It's a difficult question!

I tried the following:

example "#1. You're smart!\n#2. It's a difficult question!"

An error: -bash: !\n#2.: event not found

Then I tried to escape ! by single quote, and tried:

example '#1. You're smart\!\n#2. It's a difficult question\!'

It outputs:

${1}

Any solution here? Thanks a lot!

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-07-20 03:34

What's inside a $'' expression has to be a literal. You can't expand other variables inside it.

But you can do this:

echo "${1//\\n/$'\n'}"

Jan Hudec has an even better answer:

echo -e "$1"
查看更多
叛逆
3楼-- · 2019-07-20 03:38
$ cat t.sh
#! /bin/bash
echo -e $@

Or echo -e $1, or echo -e ${1} if you just want to process the first argument.

To get bash to stop trying to expand !, use set +H (see In bash, how do I escape an exclamation mark?)

$ set +H
$ ./t.sh "#1. You're smart!\n#2. It's a difficult question!"
#1. You're smart!
#2. It's a difficult question!
查看更多
登录 后发表回答