0

Why am I unable to have the output to a file, dir_, from shell script ?

Here is the command in script:

userid]# vi script.sh

#! /bin/bash
echo `grep -w 7171 $ABC` > /home/username/dir/dir_$(date +%Y%m%d_%H%M%S).csv

userid]# ./script.sh ./script.sh: line 13: /home/username/dir/dir_20141201_160840.csv: No such file or directory

Well I expected the script to create a new file.

Please advise the workaround.

Regards, Ashish

6
  • Does /home/username/dir exist? Also that echo is entirely unnecessary and actively causes issues with spaces in the grep results. Commented Dec 1, 2014 at 15:34
  • yes, /dir does exists. So, how better should it be written ? Commented Dec 1, 2014 at 15:35
  • 1
    grep -w 7171 "$ABC" > ... there's literally no need for echo there. Commented Dec 1, 2014 at 15:37
  • 1
    And if /home/username/dir exists then you should check permissions on it but I would expect a different error from that scenario in most cases. Commented Dec 1, 2014 at 15:38
  • Thanks. But when I run grep -w 7171 "$ABC" > WHERE $ABC is a file name, it throws an ERROR: grep: : No such file or directory Commented Dec 1, 2014 at 15:51

2 Answers 2

1

How about

([ ! -d /home/username/dir/ ] && mkdir /home/username/dir/) && grep -w 7171 $ABC > /home/username/dir/dir_$(date +%Y%m%d_%H%M%S).csv
  • [ ! -d /home/username/dir/ ] test if the directory exists

  • mkdir /home/username/dir/ creates the directory if it doesnt exist.

  • rep -w 7171 $ABC > /home/username/dir/dir_$(date +%Y%m%d_%H%M%S).csv grep the result to the file

Sign up to request clarification or add additional context in comments.

Comments

0

Probably because dir does not exist. You will have to create it:

~$ echo "a" > f
~$ echo "a" > dir/f
-bash: dir/f: No such file or directory
~$ mkdir dir
~$ echo "a" > dir/f
~$

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.