在while循环中隐藏子目录

时间:2016-07-14 14:00:52

标签: linux bash

我需要创建一个创建软/符号链接的脚本,但是还应检测'〜/ linkedfiles'目录中是否已存在链接,但问题是$ file还包含子目录。 ($ file看起来像这样:'〜/ realfiles / files / file23.gz',但我只需要'file23.gz'。)所以我的问题是,如何删除$ file中的子目录?

以下是一些代码示例:

for file in ~/realfiles/files/*.gz
do

echo "Linking file: $file"
ln -s $file ~/linkedfiles
if [ $? -ne 0 ]; then
echo "[FAIL] Linking of $file failed!"
else
echo "[SUCCESS] $file successfully linked."
fi
done

3 个答案:

答案 0 :(得分:1)

您似乎想要路径的基本名称。有两种方法可以做到这一点 - 经典可靠的方法是basename命令,而现代的不可靠方式是shell parameter expansion

for file in ~/realfiles/files/*.gz
do
    echo "Linking file: $file"
    ln -s "$file" "~/linkedfiles/$(basename "$file")"
    if [ $? -ne 0 ]
    then echo "[FAIL] Linking of $file failed!"
    else echo "[SUCCESS] $file successfully linked."
    fi
done

或者:

for file in ~/realfiles/files/*.gz
do
    echo "Linking file: $file"
    ln -s "$file" "~/linkedfiles/${file##*/}"
    if [ $? -ne 0 ]
    then echo "[FAIL] Linking of $file failed!"
    else echo "[SUCCESS] $file successfully linked."
    fi
done

在这两个脚本中,文件~/realfiles/files/file23.gz将链接到~/linkedfiles/file23.gz,这是我认为您所追求的(尽管有提高问题清晰度的空间,例如引用样本文件名的所需结果。)

答案 1 :(得分:0)

对原始脚本进行轻微修改

for filename in ~/realfiles/files/*.gz
do
echo "Linking file: $file"
[[ -h "~/linkedfiles/${var##*/}" ]] && continue
ln -s "$filename" ~/linkedfiles/
if [ $? -ne 0 ]
then
  echo "[FAIL] Linking of $filename failed!"
else
  echo "[SUCCESS] $filename successfully linked."
fi
done

备注

答案 2 :(得分:0)

targetdir="$HOME/linkedfiles"    
for filename in $HOME/realfiles/files/*.gz; do
    # if filename is a regular file then ...
    if [[ -f "${filename}" ]]; then
        # if softlink does not exist in target then link it
        if [[ ! -h "${targetdir}/${filename##*/}" ]]; then
            echo "Linking ${filename}"
            ln -s "${filename}" "${targetdir}"
            (( $? == 0 )) && echo 'Link created' || echo 'Create link fails'
        else
            echo "Skipping because ${filename##*/} exists in ${targetdir}"
        fi
    fi
done