2

I'm having an issue with pipping the results from the below script to a file. When I run the below script, nothing is written to the filecheck_output file.

#!/bin/bash

cd /var/www/html/images/
results="$(find projects -name "*.*" | sort -n)"

echo "${results}" > filecheck_output

The name of the script is filecheck. When I remove the > filecheck_output section from the end of the script and run ./filecheck > filecheck_output from the command line, the script runs and outputs the results into the filecheck_output file without any issues.

Why will the output only be redirected when I run the command from the command prompt and not from in the script?

2
  • 3
    sorry if this is obvious, but are you looking in /var/www/html/images/ , or your /home dir or /usr/local/bin or wherever filecheck is being stored. It should be in /var/www/html/images/. AND be sure you're not getting a permissions error message when running as a script. Good luck. Commented Oct 11, 2016 at 12:45
  • 1
    @shellter - I think you should post it as an answer. Commented Oct 11, 2016 at 13:28

2 Answers 2

1

Like others have mentioned, you'll want to put the full path, or relative path of filecheck_ouput into your script.

#!/bin/bash

cd /var/www/html/images/
results="$(find projects -name "*.*" | sort -n)"

echo "${results}" > /home/fedorqui/filecheck_output
Sign up to request clarification or add additional context in comments.

Comments

1

Your terminology is off. You want to redirect output to a file. To pipe something means to take the output from one command and feed it to another, like you are doing in find | sort.

Capturing the results in a temporary variable is simply wasteful, so you are really looking just for

find projects -name "*.*" | sort -n >filecheck_output

The script performs a cd earlier on, so the output file will obviously be created in that directory. If you want to avoid that, either don't cd, or do the cd in a subshell.

( cd somewhere; find projects ) | sort -n >filecheck_output

find somewhere/projects | sort -n >filecheck_output

In the latter case, the output from find will include somewhere in the path of every generated result. You can postprocess with sed to remove it like I show here, although that seems more brittle than the subshell solution.

find somewhere/projects | sed 's%^somewhere/%%' | sort -n

Not doing the redirection in the script itself seems like the best way to make it reusable; then you can choose a different output file each time you run it, if you like, so that makes it usable e.g. in a while loop over a set of directories, or whatever.

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.