Search code examples
linuxbashls

how to pass asterisk into ls command inside bash script


Hi… Need a little help here…

I tried to emulate the DOS' dir command in Linux using bash script. Basically it's just a wrapped ls command with some parameters plus summary info. Here's the script:

#!/bin/bash

# default to current folder 
if [ -z "$1" ]; then var=.;
  else var="$1"; fi

# check file existence
if [ -a "$var" ]; then
  # list contents with color, folder first
  CMD="ls -lgG $var --color --group-directories-first"; $CMD;

  # sum all files size
  size=$(ls -lgGp "$var" | grep -v / | awk '{ sum += $3 }; END { print sum }')
  if [ "$size" == "" ]; then size="0"; fi 

  # create summary
  if [ -d "$var" ]; then 
    folder=$(find $var/* -maxdepth 0 -type d | wc -l)
    file=$(find $var/* -maxdepth 0 -type f | wc -l)
    echo "Found: $folder folders "
    echo "       $file files $size bytes" 
  fi 
# error message 
else 
  echo "dir: Error \"$var\": No such file or directory"
fi

The problem is when the argument contains an asterisk (*), the ls within the script acts differently compare to the direct ls command given at the prompt. Instead of return the whole files list, the script only returns the first file. See the video below to see the comparation in action. I don't know why it behaves like that.

Anyone knows how to fix it? Thank you.

Video: problem in action


UPDATE:

The problem has been solved. Thank you all for the answers. Now my script works as expected. See the video here: http://i.giphy.com/3o8dp1YLz4fIyCbOAU.gif


Solution

  • The asterisk * is expanded by the shell when it parses the command line. In other words, your script doesn't get a parameter containing an asterisk, it gets a list of files as arguments. Your script only works with $1, the first argument. It should work with "$@" instead.