开发者

Linux Shell Script: list contents of a directory into a file

i have to write a shell script that gets a directory name as a parameter and then lists the names and sizes of the files in the directory into a text file. I have little knowledge of linux so can you please help me?

All i managed to write is this:

for entry in "$search_dir"/* 
do
  if [ -f "$entry" ];then开发者_开发技巧
    echo "$entry"
  fi
done

The output file should look like this:

filename1 filesize1
filename2 filesize2

I have problems about getting the directory name as a parameter


You could easily put the output of a script into a file using >

For example

ls /tmp > ./contentsOfDir.txt

will dump the ls command into the contentsOfDir.txt in your current directory.

The script could look like this for a bash shell:

#!/bin/bash
ls -l $1 > contentsOfDir.txt

and is called

./myScript dirNameToBeDumpedInFile

Have a look at this bash scripting tutorial, it covers the basics.


If you want to print a pretty tree of the folder content and it's subfolders, you can use "tree".

If it's not install on your system, You need to do so first:

sudo apt-get install tree

Then the syntax is pretty simple. If you want to save the output to a file:

tree -h -A path/to/dir > output.txt
  • -A is used to make sure the output is using ASCII characters.
  • -h will print each file size in a human readable format.

You have more options to limit the output that you can get by using the "--help" option:

> tree --help
  -a            All files are listed.
  -d            List directories only.
  -l            Follow symbolic links like directories.
  -f            Print the full path prefix for each file.
  -L level      Descend only level directories deep.
  -o filename   Output to file instead of stdout.
  -s            Print the size in bytes of each file.
  -h            Print the size in a more human readable way.
  --dirsfirst   List directories before files (-U disables).


like this:

#! /bin/bash
if [ $# -gt 0 ] ; then
   ls $1 > textfile.txt
else
    echo "Please provide Foldername";
fi

additionally you could check if $1 is a folder but this should suffice


#!/bin/sh

if [ ! -d "$1" ]; then
  echo "usage: $0 <directory>";
  exit 1;
fi

cd $1;
find -maxdepth 1 -type f -print0 | xargs -0 -n1 du -h;
cd -;

this will output something like:

4.0K    ./bundle.h
24K ./walker.o
4.4M    ./git-show
4.0K    ./sha1-lookup.h
100K    ./refs.o
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜