2015-10-15 65 views
0

當我嘗試做在bash shell中的子串在解釋模式下,我得到預期的輸出慶典子在翻譯模式,但不是在shell腳本工作

bash-4.2$ x="SomeString" 
bash-4.2$ echo $x 
SomeString 
bash-4.2$ y=${x:0:4} 
bash-4.2$ echo $y 
Some 
bash-4.2$ 

而同時運行在一個shell腳本相同的命令,我收到一個錯誤。

bash-4.2$ cat shell.sh 
x="SomeString" 
echo $x 
y=${x:0:4} 
echo $y 

bash-4.2$ sh shell.sh 
SomeString 
shell.sh[3]: y=${x:0:4}: 0403-011 The specified substitution is not valid for this command. 
bash-4.2$ 

具有諷刺意味的是,當我調用由bash-4.2$ ./shell.sh外殼,它的工作。

這裏發生了什麼?

我在一臺AIX機器上。

+4

'/斌/ sh'!='/斌/ bash' –

+1

擊行爲不同/manual/bash.html#Bash-POSIX-Mode)。在某些系統上,'/ bin/sh'與'/ bin/bash'完全不一樣;它可能是'dash'或原始的Bourne shell,或者......在AIX上,'/ bin/sh'可能是一個Korn shell。至少,在我現在使用的AIX機器上,'/ bin/sh'和'/ bin/ksh'具有相同的inode編號。用合適的shebang啓動你的腳本:'#!/ bin/bash'或任何正確的Bash路徑, –

回答

3

子串是bash擴展名。當你運行它作爲sh時,它將禁用此擴展。使用bash shell.sh,它會工作。

您還應該在腳本的開頭放置#!/bin/bash,以確保它在您將其作爲命令調用時以bash運行。當爲[`/斌/ sh`或`sh`](https://www.gnu.org/software/bash調用

相關問題