到目前为止我有这个
#!/bin/bash
printf -x "What file are you looking for?: " read x
if [ -x x.txt ]
then
echo "ok"
else
echo "nok"
fi
但我不知道下一步该怎么做,我需要让用户输入一个文件,我需要它来检查我认为存在的文件是否存在,然后我需要它来验证它是否存在,或者我需要它创建一个具有该名称的空白文件。我对 Shell 脚本和 Bash 脚本真的很陌生,所以如果这是非常基础的,我很抱歉
答案1
尝试反转 if 操作,通过检查用户输入的文件是否不存在。您可以使用!
“not”逻辑运算来否定它。
#!/bin/bash
printf "What file are you looking for ?\n"
read file
if [ ! -f $file ]; then
printf "%s doesn't exist, creating the file..\n" "$file"
touch $file
else
printf "%s already exist !\n" "$file"
fi
结果。
$ ls
file1 test.sh
$ ./test.sh
What file are you looking for ?
file1
file1 already exist !
$ ./test.sh
What file are you looking for ?
file2
file2 doesn't exist, creating the file..
$ ls
file1 file2 test.sh