列出给定路径的文件夹的绝对路径 - shell



我想使用 shell 脚本列出给定路径中所有文件夹的绝对路径。

我尝试的是:

ls -l /var/www/temp

但是我找不到ls命令的选项,该命令将列出绝对路径。

我在 StackOverflow 中发现了一个相关的问题:如何在 linux 中列出目录中文件夹的完整路径?

但是我需要的是在一个命令本身中,我需要列出给定路径中的所有文件夹(此路径有所不同(及其绝对路径。

谁能帮我做到这一点?提前谢谢。

这将有所帮助,但它不使用">ls">

您可以使用 pwd 与查找的替换。

   find /var/www/temp -type d

但请注意,这将在屏幕上输出列表。

外壳函数怎么样?

dabspath () {
if [ -d "$1" ]
then
    cd "$1"
    find "$PWD" -type d
    cd "$OLDPWD"
else
    echo "$0: $1: No such directory"
fi
}

用法:dabspath foo

如果foo是相对于当前工作目录的目录,那么它将打印foo和任何子目录的绝对路径。

for D in `find . -maxdepth 1 -type d`; do echo $PWD${D#.}; done

工作原理:

  1. 首先,bash 将在反引号内运行 find 命令,并将反引号中的部分替换为 find 返回的内容,这些返回是工作目录的所有直接子目录的名称。
  2. 接下来,for 循环将遍历所有子目录,对于存储在变量 D 中的每个子目录,它将打印工作目录 ($PWD( 的路径,后跟子目录 D,从中删除 prexif "."。这样,绝对路径将按预期打印。

注意:由于每个目录都有一个指向自身的硬链接("." 子目录(,因此它还将打印工作目录的路径。

此脚本列出所有目录,或者(可选(列出-type T选项find识别的所有任何类型的目录。 默认情况下,如果未提供参数,它将列出当前目录中的所有目录。 若要列出绝对路径,请将绝对路径作为目标目录传递。

#!/bin/bash
# usage: ${0} [-type [fd]] [-l] <directory>
_TYPE="d" # if f, list only files, if d, list only directories
let _long=0
let _typeflag=0
# collect dirs and files
DIRS=( ) ; FILS=( )
for A in "$@" ; do
  if [ $_typeflag -eq 1 ]; then
    _TYPE=$A
    let _typeflag=0
  elif [ -d "$A" ]; then
    DIRS=( ${DIRS[@]} "$A" )
  elif [ -f "$A" ]; then
    FILS=( ${FILS[@]} "$A" )
  else
    case "$A" in
    "-type") let _typeflag=1 ;;
    "-l") let _long=1 ;;
    *) echo "not a directory: [$A]" 1>&2
      exit 1
      ;;
    esac
  fi
done
# list files in current dir, if nothing specified
[ ${#DIRS[@]} -eq 0 ] && DIRS=( "$(pwd -P)" )
if [ $_long -eq 0 ]; then
  find ${DIRS[@]} -maxdepth 1 -type $_TYPE | while read F ; do
    if [[ "$F" != "." && "$F" != ".." ]]; then
      echo ""$F""
    fi
  done | xargs ls -ltrad --time-style=long-iso | sed 's#.*:[0-9][0-9] ##'
else
  find ${DIRS[@]} -maxdepth 1 -type $_TYPE | while read F ; do
    echo ""$F""
  done | xargs ls -ltrad --time-style=long-iso
fi

相关内容

最新更新