1

Let's say I write the following script:

#!/bin/sh
TEXT="hello"
DIR="test"
FILE="bla.txt"
echo $TEXT > $DIR/$FILE

When running it, I get the following error:

test.sh: line 5: test/bla.txt: No such file or directory

But if change the last line to:

echo $TEXT > $FILE

I don't get the error.

I know I can work around it and do:

FILE_TO_WRITE_TO=$DIR/$FILE
echo $TEXT > $FILE_TO_WRITE_TO

But I don't understand why does the error occur in the first place.

3
  • Try this: mkdir "$DIR" Commented Jul 8, 2017 at 16:32
  • Tried it on my system and it works perfectly fine Commented Jul 8, 2017 at 16:34
  • Never mind, I have no idea why it didn't work right before I asked the question.. Commented Jul 8, 2017 at 16:40

1 Answer 1

2

The following command gives No such file or directory error because test directory doesn't exist or Not a directory if it is not a directory.

echo "hello" > test/bla.txt

To create the directory if necessary, and error management.

mkdir -p "$DIR" || { echo "failed to mkdir $DIR"; exit 1;}
echo "$TEXT" > "$DIR/$FILE" || { echo "failed to open $DIR/$FILE for writting"; exit 1;}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.