2015-12-30 48 views
-1

當我讀的書linux的shell腳本食譜 他們說,當你想打印!,你不應該把它放在雙引號,或者您也可以!前添加\逃脫它。 例如Linux終端執行回聲功能

  1. $echo "Hello,world!"
  2. 慶典::事件未找到錯誤
  3. $echo "Hello,world\\!"
  4. 你好,世界!

,但在我的情況(ubuntu14.04),我得到的答案類似:

  1. $echo "Hello,world!"
  2. 你好,世界!
  3. $echo "Hello,world\\!"
  4. 你好,世界\!

那麼,爲什麼我的機器無法得到相同的答案?

爲什麼轉義符號\被打印爲正常符號?

+1

什麼是你的問題? –

+0

sry,我編輯它 –

回答

2

當您以交互方式鍵入shell時,!有特殊含義,它是history expansion character。爲了防止這種特殊含義,您需要將其放在單引號中或轉義。

echo 'Hello, world!' 
echo "Hello, world\!' 

它不是在Ubuntu上發生的事情可能是因爲它的運行的bash更新的版本,這顯然是更有選擇性的歷史時,發生膨脹有關的原因。似乎需要!後跟字母數字,而不是標點符號。

您不需要在腳本中執行此操作,因爲歷史記錄通常不會在此處啓用。它只是用於交互式shell。

+0

歷史擴張只有在'!'的RHS上有一些非空格的文本時纔會發生 – anubhava

+0

@anubhava doublequotes是非空格文本。 – Barmar

+0

不確定是因爲'echo「你好,世界!」''爲我打印'Hello,world!'但是'echo「你好,世界!你好」'說''-bash:!hello:event not found' – anubhava

0

創建一個shell腳本調用file.sh:

#!/bin/bash 
# file.sh: a sample shell script to demonstrate the concept of Bash shell functions 
# define usage function 
usage(){ 
    echo "Usage: $0 filename" 
    exit 1 
} 

# define is_file_exits function 
# $f -> store argument passed to the script 
is_file_exits(){ 
    local f="$1" 
    [[ -f "$f" ]] && return 0 || return 1 
} 
# invoke usage 
# call usage() function if filename not supplied 
[[ $# -eq 0 ]] && usage 

# Invoke is_file_exits 
if (is_file_exits "$1") 
    then 
    echo "File found" 
else 
    echo "File not found" 
fi 

運行它,如下所示

chmod +x file.sh 
./file.sh 
./file.sh /etc/resolv.conf