如何将ls命令的结果重定向为read-a命令作为单个字符串



我使用的是基于Red Hat的Linux。我使用这个bash脚本来查找所有USB设备,并将其放置在selectList:中

read -a devices <<< $(ls -l --time-style=long-iso /dev/disk/by-id)
while [[ ${devices[i]} != "" ]]
do
if [[ ${devices[i]} == usb-* ]] ; 
then
if [[ ! ${devices[i+2]} =~ [0-9]$ ]] ; 
then
selectList+=${devices[i]}" "
fi
fi
let "i++"
done

对于旧的Linux发行版(旧的Fedora,CentOS 7(,它可以正常工作。但在Fedora 32上,这个字符串不起作用:

read -a devices <<< $(ls -l --time-style=long-iso /dev/disk/by-id)

因为

<<< $(ls -l --time-style=long-iso /dev/disk/by-id)

只返回结果ls命令的第一个字符串。

例如,命令

tail -n1 <<< $(ls -l --time-style=long-iso /dev/disk/by-id)

在CentOS 7 上返回

total 0 lrwxrwxrwx 1 root root 9 2020-07-14 10:23 ata-Optiarc_DVD_RW_AD-5280S -> ../../sr0 lrwxrwxrwx 1 root root 9 2020-07-14 10:23 ata-ST3500514NS_9WJ16TBB -> ../../sda lrwxrwxrwx 1 root root 9 2020-07-14 10:23 ata-ST500DM002-1BD142_Z3T5RLF8 -> ../../sdb lrwxrwxrwx 1 root root 11 2020-07-14 10:23 md-uuid-6a3d48a2:fbd5af07:9ce92935:f469dfc7 -> ../../md127 lrwxrwxrwx 1 root root 11 2020-07-14 10:23 md-uuid-721d0cf4:5fc67883:dbbd7d4c:47ff4941 -> ../../md126 lrwxrwxrwx 1 root root 13 2020-07-14 10:23 md-uuid-721d0cf4:5fc67883:dbbd7d4c:47ff4941-part1 -> ../../md126p1 lrwxrwxrwx 1 root root 13 2020-07-14 10:23 md-uuid-721d0cf4:5fc67883:dbbd7d4c:47ff4941-part2 -> ../../md126p2 lrwxrwxrwx 1 root root 13 2020-07-14 10:23 md-uuid-721d0cf4:5fc67883:dbbd7d4c:47ff4941-part3 -> ../../md126p3 lrwxrwxrwx 1 root root 13 2020-07-14 10:23 md-uuid-721d0cf4:5fc67883:dbbd7d4c:47ff4941-part4 -> ../../md126p4 lrwxrwxrwx 1 root root 13 2020-07-14 10:23 md-uuid-721d0cf4:5fc67883:dbbd7d4c:47ff4941-part5 -> ../../md126p5 lrwxrwxrwx 1 root root 9 2020-07-14 10:23 wwn-0x5000c5002e22dc64 -> ../../sda lrwxrwxrwx 1 root root 9 2020-07-14 10:23 wwn-0x5000c5004e81f353 -> ../../sdb

但在Fedora 32上,它返回

lrwxrwxrwx 1 root root 9 2020-07-14 10:23 wwn-0x5000c5004e81f353 -> ../../sdb

问题已解决。此脚本允许用户选择USB闪存,并将设备的路径放入$deviceName变量中。

for device in /dev/disk/by-id/*; 
do 
if [[ $device == /dev/disk/by-id/usb-* ]] ;
then
device1=${device/"/dev/disk/by-id/"/}

read -a devices <<< $(ls -l --time-style=long-iso /dev/disk/by-id | grep $device1)
if [[ ! ${devices[9]} =~ [0-9]$ ]] ; 
then
selectList+=${devices[7]}"->/dev/"${devices[9]##*/}" "
fi
fi
done
if [ "$selectList" = "" ] ; then
echo -e "ERROR: No USB devices foundnr"
exit 1
fi
echo "select the USB device"
select usbName in $selectList
do
if [[ $usbName != "" ]] ;
then
break
else
echo "wrong USB device number"
fi
done
deviceName="/dev/"${usbName##*->/dev/}

最新更新