我正在学习 bash,在尝试编写小脚本时遇到了一个小问题
#!/bin/bash
clear
read num
if [ "$num" -eq 2 ]
then [ -d "/etc/passwd" ] | sudo cp /etc/passwd /home
echo -e "${lred}The passwd file has been copied to your home directory. ${NC}"
else
echo "The directory does not exist"
fi
我遇到的问题是我想要检查目录,否则在尝试运行复制命令时显示第二个回显“目录不存在”。我得到“cp:无法 stat '/et/passwd':没有这样的文件或目录”,但第一个回显指出“passwd 文件已复制到您的主目录。”仍然显示,而第二个回显“文件不存在”则不显示。如果有人有解决方案,我真的很感激。谢谢!
编辑:这是我的整个脚本
#!/bin/bash
clear
lred='\033[1;31m'
red='\033[0;31m'
NC='\033[0m' # No Color
blue='\033[0;34m'
lblue='\033[1;34m'
echo -e "${red}Welcome to Lab 7 Utilities Menu ${NC}" # tells echo to enable backslash escapes
sleep 3
clear
echo -e "${lblue}Choose one of the options from the following list:${NC}"
echo -e "${blue}1. Monitor existing processes ${NC}"
echo -e "${blue}2. Copy passwd to /home directory ${NC}"
echo -e "${blue}3. Ping local host ${NC}"
echo -e "${lred}4. Exit ${NC}"
read num
if [ $num -eq 1 ]
then ps aux
echo -e "${lred}The list has been successfully generated! ${NC}"
fi
if [ "$num" -eq 2 ]; then
if [ -e "/etc/passwd" ]; then
sudo cp /etc/passwd /home
echo -e "${lred}The passwd file has been copied to your home directory. ${NC}"
else
echo "The File does not exist"
fi
else
echo "You entered number that isn't 2"
fi
if [ "$num" -eq 3 ]
then ping -c 4 127.0.0.1
echo -e "${lred}You have completed pinging localhost. ${NC}"
elif [ "$num" -eq 4 ]
then clear
elif [ "$num" -gt 4 ]
then echo -e "${red}Please choose between number 1 and 4. ${NC}"
clear
fi
答案1
更新(来自我们的聊天),我认为案例陈述更适合您在这里想要完成的任务:
#!/bin/bash
clear
lred='\033[1;31m'
red='\033[0;31m'
NC='\033[0m' # No Color
blue='\033[0;34m'
lblue='\033[1;34m'
# tells echo to enable backslash escapes
echo -e "${red}Welcome to Lab 7 Utilities Menu ${NC}"
sleep 3
clear
echo -e "${lblue}Choose one of the options from the following list:${NC}"
echo -e "${blue}1. Monitor existing processes ${NC}"
echo -e "${blue}2. Copy passwd to /home directory ${NC}"
echo -e "${blue}3. Ping local host ${NC}"
echo -e "${lred}4. Exit ${NC}"
read num
case $num in
1)
ps aux
echo -e "${lred}The list has been successfully generated! ${NC}"
;;
2)
if [ -e "/etc/passwd" ]; then
sudo cp /etc/passwd /home
echo -e "${lred}The passwd file has been copied to your home directory. ${NC}"
else
echo "The File does not exist"
fi
;;
3)
ping -c 4 127.0.0.1
echo -e "${lred}You have completed pinging localhost. ${NC}"
;;
4)
clear
;;
*)
echo -e "${red}Please choose between number 1 and 4. ${NC}"
;;
esac
您确定要将passwd
文件复制到该/home
目录吗?除此之外,这应该有效:
#!/bin/bash
clear
read num
if [ "$num" -eq 2 ]; then
if [ -e "/etc/passwd" ]; then
sudo cp /etc/passwd /home
echo -e "${lred}The passwd file has been copied to your home directory. ${NC}"
else
echo "The File does not exist"
fi
else
echo "You entered a number that isn't '2'"
fi
该-d
参数检查是否FILE exists and is a directory
。你想要的是-e
哪个检查FILE exists
。
此外,您还尝试|
在 后进行管道传输then
,这会导致更多冲突,因为它不适合您尝试执行的操作。