Bash - Initialize variable to output of command “permission denied”

会有一股神秘感。 提交于 2020-01-30 08:54:25

问题


I'm writing a small bash script to get the number out of each file name. For example the file name helloworld1.txt would produce 1.

When attempting to set the output to the variable i I get an error for each file.

line 5: 985.txt: Permission denied

If I just echo the command echo $f | tr -dc '[0-9]' rather than assign it to a variable, everything is good.

#!/bin/bash

for f in *
do
        i=`$f | tr -dc '[0-9]'` // Permission denied.
        echo $i
done

回答1:


You have missed echo here. The line

i=`$f | tr -dc '[0-9]'`

should be

i=`echo $f | tr -dc '[0-9]'`



回答2:


The line in the loop without a subshell, pipe and additional process per file:

i=${f//[^0-9]/}

The parameter substitution removes all non-digits.



来源:https://stackoverflow.com/questions/23108816/bash-initialize-variable-to-output-of-command-permission-denied

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!