我对linux脚本编程非常陌生。我正在尝试建立一个简单的循环:
这是我到目前为止所做的,但它根本没有循环(即没有找到文件时,它不会要求用户重新输入文件名。)
#!/bin/bash
read -p "Enter file name: " file
find /directory/ -name "$file" -print
while [ "$?" -ne 0 ]; do
read -p "File not found. Please re-enter file name: " file
find /directory/ -name "$file" -print
done
echo "rest of script etc"
任何帮助表示赞赏! :)
答案 0 :(得分:1)
最简单的方法是使用globstar(bash 4提供)
#!/bin/bash
shopt -s globstar
while true; do
read -p "Enter file name: " file
for f in /directory/**/"$file"; do
echo "$f"
break 2 # escape both loops
done
echo "'$file' not found, please try again."
done
echo "rest of script etc"
它也可能与find
有关,但有点烦人,因为你不能使用标准的UNIX退出状态:
#!/bin/bash
read -p "Enter file name: " file
found=$(find /directory/ -name "$file" -print -quit)
while [[ -z $found ]]; do
read -p "File not found. Please re-enter file name: " file
found=$(find /directory/ -name "$file" -print -quit)
done
echo "$found"
echo "rest of script etc"
通常我不建议解析find
的输出,但在这种情况下,我们只关心是否有任何输出。
答案 1 :(得分:-1)
最简单,最便携的方式可能是:
# Loop until user inputted a valid file name
while true ; do
# Read input (the POSIX compatible way)
echo -n "Enter file name: "
read file
# Use find to check if the file exists
[ $(find /etc -type f -name "$file" 2>/dev/null | wc -l ) != "0" ] && break
# go to next loop if the file does not exist
done
echo "Ok, go on here"