我在编写将命令输出的每一行保存#mount | grep ^\/dev/
到变量中的 bash 脚本时遇到问题。
下面是我的 bash 脚本。
#!/bin/bash
mount | grep ^\/dev/ > tempoary
input=$(cat tempoary)
x=0
while IFS= read -r line
do
x=$((x+1))
echo "$line" > /tmp/directory/$x
for file in $(echo "$line"); do
eval "var$x=$file";
echo "$file"
done
done <<< "$input"
输出如下:
[root@localhost tmp]# sh script
/dev/mapper/rhel-root
on
/
type
xfs
(rw,relatime,seclabel,attr2,inode64,noquota)
/dev/sda1
on
/boot
type
xfs
(rw,relatime,seclabel,attr2,inode64,noquota)
我希望有这样的输出格式:
[root@localhost tmp]# sh script
/dev/mapper/rhel-root on / type xfs (rw,relatime,seclabel,attr2,inode64,noquota)
/dev/sda1 on /boot type xfs (rw,relatime,seclabel,attr2,inode64,noquota)
您能给我一些指导,告诉我如何实现这一目标吗?
附言。双引号"$(echo "$line")"
没有帮助,只会提示下面的语法错误。
[root@localhost tmp]# sh script
script: eval: line 14: syntax error near unexpected token `('
script: eval: line 14: `var1=/dev/mapper/rhel-root on / type xfs (rw,relatime,seclabel,attr2,inode64,noquota)'
答案1
将文件直接重定向到while ... done
:
mount | grep ^\/dev/ > tempoary
while IFS= read -r line
do
...
done < temporary
或使用进程替换来省略临时文件:
while IFS= read -r line
do
...
done < <(mount | grep ^\/dev/)
或类似地通过管道传递给 while
mount | grep ^\/dev/ |
while IFS= read -r line
do
...
done
答案2
在 for 循环之前添加 IFS 并引用文件变量使一切正常......看看这个:
#!/bin/bash
mount | grep ^\/dev/ > tempoary
input=$(cat tempoary)
x=0
while IFS= read -r line
do
x=$((x+1))
echo "$line" > /tmp/tmp/$x
IFS=
for file in $(echo "$line"); do
eval "var$x='$file'";
echo "$file"
done
done <<< "$input"
答案3
根据评论
输出为“/dev/mapper/rhel-root on / type xfs (rw,relatime,seclabel,attr2,inode64,noquota)”和“/dev/sda1 on /boot type xfs (rw,relatime,seclabel,attr2, inode64,noquota)”分别。将这两行保存到变量1和变量2后
标准变量不一定是最佳答案。相反,大批更有可能是你想要的。
例如:
#!/bin/bash
typeset -A mounts
let index=0
m=$(mount | grep "^/dev/")
while read line
do
mounts[$index]="$line"
let index=index+1
done <<< "$m"
echo There were $index lines
let a=0
while [ $a -lt $index ]
do
echo Line $a was ${mounts[$a]}
let a=a+1
done
在我的机器上,如果我运行这个,我会得到
There were 4 lines
Line 0 was /dev/vda3 on / type ext4 (rw,relatime,data=ordered)
Line 1 was /dev/vda1 on /boot type ext4 (rw,relatime,data=ordered)
Line 2 was /dev/vdb on /news type ext3 (rw,relatime,data=ordered)
Line 3 was /dev/vdc1 on /brick type ext3 (rw,relatime,data=ordered)