0

我正在研究“Beginning Linux Programming 4th ed”一书,第 2 章是关于 shell 编程的。第 53 页上的示例给我留下了深刻的印象,并尝试开发一个脚本来显示更多内容。这是我的代码:

enter code here
#!/bin/bash
var1=10
var2=20
var3=30
var4=40
for i in 1 2 3 4 # This works as intended!
do
    x=var$i
    y=$(($x))
    echo $x = $y   # But we can avoid declaring extra parameters x and y, see next line
    printf "  %s \n" "var$i = $(($x))"
done
for j in 1 2 3 4  #This has problems!
do
    psword=PS$j
    #eval psval='$'PS$i   # Produces the  same output as the next line
    eval psval='$'$psword
    echo '$'$psword = $psval 
    #echo "\$$psword = $psval"    #The same as previous line
    #echo  $(eval '$'PS${i})   #Futile attempts
    #echo PS$i =  $(($PS${i}))
    #echo PS$i =  $(($PS{i}))
done

#I can not make it work as I want : the output I expect is
#PS1 = \[\e]0;\u@\h: \w\a\]${debian_chroot:+($debian_chroot)}\u@\h:\w\$
#PS2 = >
#PS3 = 
#PS4 = + 

如何获得预期的输出?当我按原样运行它时,我只会得到

PS1 = 
PS2 = 
PS3 = 
PS4 = +

PS1 和 PS2 发生了什么?为什么我没有得到与我得到的相同的价值

echo $PS1
echo $PS2
echo $PS3
echo $PS4

因为那是我想要得到的。

4

2 回答 2

1

运行脚本的 shell 始终是非交互式 shell。您可以使用“-i”选项强制以交互模式运行脚本:

尝试改变:

#!/bin/bash

至:

#!/bin/bash -i

请参阅“man bash”中的 INVOCATION 部分(bash.bashrc 是定义 PS1 的位置):

       When an interactive shell  that  is  not  a  login  shell  is  started,  bash  reads  and  executes  commands  from
   /etc/bash.bashrc  and  ~/.bashrc,  if  these  files  exist.  This may be inhibited by using the --norc option.  The
   --rcfile file option will force bash to read and  execute  commands  from  file  instead  of  /etc/bash.bashrc  and
   ~/.bashrc.

   When  bash  is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in
   the environment, expands its value if it appears there, and uses the expanded value as the name of a file  to  read
   and execute.  Bash behaves as if the following command were executed:
          if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi
   but the value of the PATH variable is not used to search for the file name.

您还可以阅读:http ://tldp.org/LDP/abs/html/intandnonint.html

简单测试:

$ cat > test.sh
echo "PS1: $PS1"
$ ./test.sh 
PS1: 

$ cat > test.sh
#!/bin/bash -i            
echo "PS1: $PS1"
$ ./test.sh 
PS1: ${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w \$\[\033[00m\] 
于 2012-03-24T19:33:33.067 回答
0

使用间接扩展:

for j in 0 1 2 3 4; do
    psword="PS$j"
    echo "$psword = ${!psword}"
done
于 2012-03-24T18:34:31.390 回答