-2

I'm just so stressed struggling about this simple grammar. I learned in text; To store value in shell programming, we use value=$(expression). So I made following script

#!/bin/bash
address=$1
echo $address
value=$(test -d $address)
echo $value

This is a script to find if my input(directory) exists and accessible.

Address shows me the input but $value shows nothing.

At least I expected 0 or non-zero but it didn't!

Can anybody teach me how to save the result of test?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Hyun seo
  • 1
  • 3
  • A command substitution saves *standard output,* not the result code. You can certainly set `value=$?` though generally that's probably not actually what you want; see also https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern – tripleee Mar 27 '20 at 13:19
  • Also tangentially see https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable – tripleee Mar 27 '20 at 13:25
  • Thank you very much. I'll try that for sure – Hyun seo Mar 27 '20 at 13:27
  • Did you try typing the command on the bash command line? – stark Mar 27 '20 at 13:32
  • @stark yes I did. But didn't worked.. – Hyun seo Mar 27 '20 at 13:37

1 Answers1

0

test has no output, but the result of the last command is saved as $?, so you could either -

value=$(test -d $address; echo $?)

or just skip saving it and use the test.

if [ -d "$address" ]
then ...
Paul Hodges
  • 13,382
  • 1
  • 17
  • 36