gpt4 book ai didi

linux - 巴什脚本 : handling paths with escaped spaces

转载 作者:太空狗 更新时间:2023-10-29 11:22:50 25 4
gpt4 key购买 nike

我有一个 bash 脚本,我想处理空格。我知道这里有很多关于此的问题,但我无法解决我的问题。

根据我读过的内容,以下内容应该有效。中的空间../tool_profile/OS\Firmware/updater 正在转义。在脚本中,$2 变量在分配给 DEST 时用引号引起来。

如果我将此路径传递给 ls,并在命令行中用引号括起来或使用转义空格,它就可以工作。

示例脚本命令:

./make_initramfs.sh initramfs_root/ ../tool_profile/OS\ Firmware/updater/ initramfs

脚本中 ls 的错误:

ls: cannot access ../tool_profile/OS Firmware/updater/: No such file or directory

ma​​ke_initramfs.sh:

#!/bin/bash

if [ $# -ne 3 ]; then
echo "Usage: `basename $0` <root> <dest> <archive_name>"
exit 1
fi

ROOT=$1
DEST="$2"
NAME=$3

echo "[$DEST]"

# cd and hide output
cd $ROOT 2&>/dev/null

if [ $? -eq 1 ]; then
echo "invalid root: $ROOT"
exit 1
fi


ls "$2" # doesn't work
ls "$DEST" # doesn't work


# check for 'ls' errors
#if [ $? -eq 1 ]; then
# echo "invalid dest: $DEST"
# exit 1
#fi

#sudo find . | sudo cpio -H newc -o | gzip --best > "$DEST"/"$NAME"

感谢您对我做错了什么的任何线索! ^_^

最佳答案

好吧......当我提交这个时,我意识到我做错了什么。

在验证第二个之前,我传递了两个相对路径并更改为第一个。因此,一旦我更改了目录,第二个相对路径就不再有效。完成后我会发布更新的脚本。

编辑:我完成了脚本。见下文。Edit2:我根据大家的评论更新了这个。谢谢大家!

ma​​ke_initramfs.sh:

#!/bin/bash


if (( $# != 2 )); then
echo "Usage: `basename $0` <root> <dest>"
exit 1
fi

root="$1"
archive="${2##*/}"
dest="$PWD/${2%/*}"

# cd and hide errors
cd "$root" &>/dev/null
if (( $? != 0 )); then
echo "invalid path: $root"
exit 1
fi

if [ ! -d "$dest" ]; then
echo "invalid path: $dest"
exit 1
fi

if [ "$archive" = "" ]; then
echo "no archive file specified"
exit 1
fi

if [ `whoami` != root ]; then
echo "please run this script as root or using sudo"
exit 1
fi

find . | cpio -H newc -o | gzip --best > "$dest"/"$archive"

关于linux - 巴什脚本 : handling paths with escaped spaces,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11458489/

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