Como verificar se um arg é um nome de arquivo válido no Shell?
-
11-09-2019 - |
Pergunta
Eu preciso verificar se os argumentos são nomes de arquivos válidos, é este o caminho certo para fazê-lo? Parece que eu fiz algum erro linha 2, mas eu não sei onde.
for i in ${@}; do
if [ -f ${i}]; then
echo ${i}
else continue
fi
done
Solução
First of all, you need a space before the closing square bracket. And you should quote your variables in case there's a space in a filename.
for i in "${@}"; do
if [ -f "${i}" ]; then
echo "${i}"
else continue
fi
done
The "else continue
" is unnecessary, unless that's a placeholder for something else you plan to put in place of "continue
".
Outras dicas
Here is a terse solution, which works even if file names contain spaces:
for i
do
test -f "$i" && echo "$i"
done
Note that the for statement assumes the command line arguments, there is no need to type more. The test command is a short way of if .. then .. fi
-f checks that ${i} is a regular file.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow