简体   繁体   中英

how to enter a directory as a command line argument

#!/bin/bash

echo Enter a Directory Name:
read

if [ -d "$1" ];
 then
  find "$1" -type f -size 0 -delete
  find "$1" *.tmp -type f -delete
  find "$1" *.swp -type f -delete
  tar -cvzf mytarfile.tgz "$1"
else
  echo "This is not a directory"
fi

The script runs when I put in the directory myself using ./program.sh Desktop. If I have an empty txt, .tmp and .swp file on my desktop it removes them and makes a tar file. How can I enter a directory at the (read) line for example Documents or MyMusic. It allows me to type in something but then goes right to the else and prints "This is not a directory.

Replace all $1 with $REPLY .


Take a look at read's syntax: help read

You can use a variable to read the Directory name,like:

echo "Enter a Directory Name:"
read Dir_Name

or better:

read -p "Enter Directory Name:" Dir_Name

and then replace all $1 with ${Dir_Name}

$1 is a special variable in Unix. Read it here: special variables

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM