简体   繁体   English

我正在学习bash,与命令行参数混淆

[英]Im learning bash, confused with command line arguments

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. 因此,在命令行中,我应该键入./check.sh test(现有目录),脚本应该运行。 Now I don't understand how to use test which should be $1. 现在我不知道如何使用应为$ 1的测试。 In the script I want to take $1 and check it against existing directories. 在脚本中,我要使用$ 1并对照现有目录进行检查。 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. 它不起作用,因为DIR不接受参数(在本例中为test),我知道我需要使用if-else块,但我不理解如何获取所需的信息。 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 ). 或者,您可能一直使用$1 (它比$ DIR短,我更喜欢使用env搜索bash它并不总是/bin/bash )。

#!/usr/bin/env bash
if [ -d "$1" ]; then
    cd "$1"
    ls
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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