I need to create a script that allows a command line argument to be passed and checked to see if it exists as a directory within the directory im running the script in. If it does list the contents and if it doesnt print a error message. So at the command line I should type ./check.sh test(existing directory) and the script should run. Now I don't understand how to use test which should be $1. In the script I want to take $1 and check it against existing directories. however if i do something like:
#!/bin/bash
DIR=$1
cd DIR
ls
it doesn't work because DIR doesn't take on the argument(in this case test) I know I need to use an if-else block but I dont understand how to get the information I need to begin with. Please someone help me figure this out.
I think you wanted something like
#!/bin/bash
DIR="$1"
#test if $DIR is a directory.
if [ -d "$DIR" ]; then
cd "$DIR"
ls
fi
Or, you could have used $1
throughout (it's shorter than $DIR, and I would prefer to use env
to search for bash
- it isn't always /bin/bash
).
#!/usr/bin/env bash
if [ -d "$1" ]; then
cd "$1"
ls
fi
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.