如果和其他在bash不工作

时间:2013-12-03 02:55:04

标签: bash shell

我无法弄清楚我在哪里搞砸了它但它杀了我,而且我越乱越糟糕。 我正在尝试从用户获取目录并在要求目录中的搜索词之前显示它。我希望用户必须专门输入“q!”退出,否则它只是从头开始。我究竟做错了什么?提前谢谢!

#!/bin/bash
echo 'Enter directory name, pwd for present working directory, or q! for quit.'
read $dirName
echo $dirName
read -p "Press [Enter] key to continue..."
echo 'Enter part, or all of the filename'
read $fileName
echo $fileName
read -p "Press [Enter] key to continue..."
if [ "$dirName" = "q!"]; then
  exit 0
else
  ls -l $dirName
  ls -a *$fileName*
fi  

2 个答案:

答案 0 :(得分:1)

  

我希望用户必须专门输入“q!”退出,否则它   刚刚从头开始

你需要使用循环,并检查用户输入,只在用户输入"q!"时中断循环。 $(以及其他read $dirName)也不需要read

#!/bin/bash
while true
do
        echo 'Enter directory name, pwd for present working directory, or q! for quit.'
        read dirName
        [ "x$dirName" == "xq!" ] && break
        #do other stuff
done

答案 1 :(得分:0)

#!/bin/bash
echo 'Enter directory name, pwd for present working directory, or q! for quit.'
read dirName                      #<--- remove $
echo $dirName
read -p "Press [Enter] key to continue..."
echo 'Enter part, or all of the filename'
read fileName                     #<--- remove $
echo $fileName
read -p "Press [Enter] key to continue..."
if [ "$dirName" = "q!" ]; then    #<--- add space after "q!"
  exit 0
else
  ls -l $dirName
  ls -a *$fileName*
fi  

这适用于我的电脑。