gpt4 book ai didi

arrays - 如何在换行符分隔的列表中使用 bash 的选择?

转载 作者:行者123 更新时间:2023-12-02 15:09:12 26 4
gpt4 key购买 nike

如何在换行符分隔的列表中使用 bash 的选择?

我实际上是在尝试改进工作脚本中的以下代码段:

# for example
nwd=/media/$USER/some-drive

# This makes a newline-separated list. I'm open to options that make a
# list in a different fashion. I usually loop with find -print0 for this
# kind of thing, but I don't know an easy way to omit a particular
# element ($nwd) from a null-separated list.
volumes="$( ls /media/$USER | grep -v "$( basename -- "$nwd" )" )"

# If there's only one option, I don't need the user to choose.
if [ 1 -eq "$( echo "$volumes" | wc -l )" ]; then
mount_point="/media/$USER/$volumes"
else
# KNOWN BUG: It is impossible to select devices with spaces in their names.
echo "Please select the appropriate device:"
select mount_point in $volumes Quit; do
case "$mount_point" in
Quit ) exit $EXIT_USER_HALT;;
'' ) echo "Invalid option. Try another one." >&2;continue;;
* ) break;;
esac
done
mount_point="/media/$USER/$mount_point"
fi

最佳答案

使用扩展模式,您可以用所需的文件名填充数组:

shopt -s extglob
nwd=/media/$USER/some-drive
volumes=( /media/$USER/!("$(basename -- "$nwd")") )
# Or more generally,
# volumes=( "$(dirname -- "$nwd")"/!("$(basename -- "$nwd")") )

然后你可以使用这个数组作为

if (( ${#volumes[@]} == 1 )); then
mount_point="/media/$USER/$volumes" # or ${volumes[0]}
else
echo "Please select the appropriate device:"
select mount_point in "${volumes[@]}" Quit; do
case $mount_point in
Quit) exit $EXIT_USER_HALT ;;
'') echo "Invalid option. Try another one." >&2; continue ;;
*) break ;;
esac
done
fi

使用数组还修复了无法选择名称包含空格的挂载点的问题。 (事实上​​ ,它适用于任何有效的文件路径,包括那些可能包含 glob 元字符或换行符的文件路径。)

关于arrays - 如何在换行符分隔的列表中使用 bash 的选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44958941/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com