BASH script question

Hi,

I want to create a script that gets a filename as an argument.
The script should generate a listing in long list format of the current directory, sorted by file size.
This list must be written to a new file by the filename given on the command line.

Can someone help me with this?

Here is my start:

#!/bin/sh
echo "Please give in the filename"
read NEW_FILENAME
#read the current directory in long listing and sort by filesize (small to big) and writes it to the given filename
ls -l -S -r  > $NEW_FILENAME 

But I am kind of stuck.

Thanks for your help so far.

Hi
You can simple use this command, to obtain the list of extant files and directories sorted by size

ls -al | sort +4 -r > temp.log

If your OS is HP-UX, you can use:

 ll | sort +4 -r > temp.log

Regards

Hi,

I think I allready found the solution ...

#!/bin/sh
echo "Please give in the filename"
read NEW_FILENAME
#read the current directory in long listing and sort by filesize (small to big) and writes it to the given filename
ls -l -S -r  > $NEW_FILENAME

Glad you found but is you want your script to be a bash script it have to start with:
#!/bin/bash
:wink:

I am a n00b when it comes to shell scripting ... but this is one of the things you cant miss when you read teh guides and books on this subject :slight_smile:

Hi,

To add a command line arguement to a script try:

listit.sh

#!/bin/sh
if test $# -gt 0; then
target=$1;
else
echo "no output file specified using default.lst"
target=default.lst
fi
ls -l -S -r > $target

You can then run
./listit.sh myfile.lst

If you just run the script without an argument it will use the default.lst file.

If you want this to behave more like a standard unix command line tool, you might want to consider using getopts. For example:

#!/bin/bash

usage() {
cat <<EOT
Usage: `basename $0` [-f] [-o filename]

    -o file  output to filename.  Default: prompt for filename
    -f       force overwrite if output file already exist
EOT
}

filename=""
force=false
while getopts fo: opt; do
  case "$opt" in
    o) filename="$OPTARG" ;;
    f) force=true ;;
  esac
done
shift `expr $OPTIND - 1`

if [ -z "$filename" ]; then
  read -p "Enter a filename: " filename
fi

if [ -s "$filename" -a $force = "false" ]; then
  echo "ERROR: $filename exists" >&2
  exit 1
fi

ls -lSr > "$filename"