2

I'm a very new user to bash, so bear with me. I'm trying to run a bash script that will take inputs from the command line, and then run a c program which its output to other c programs. For example, at command line I would enter as follows:

$ ./script.sh -flag file1 < file2

The within the script I would have:

./c_program -flag file1 < file2 | other_c_program

The problem is, -flag, file1 and file2 need to be variable. Now I know that for -flag and file this is fairly simple- I can do

FLAG=$1
FILE1=$2
./c_program $FLAG FILE1

My problem is: is there a way to assign a variable within the script to file2?

EDIT: It's a requirement of the program that the script is called as $ ./script.sh -flag file1 < file2

0

2 Answers 2

1

You can simply run ./c_program exactly as you have it, and it will inherit stdin from the parent script. It will read from wherever its parent process is reading from.

FLAG=$1
FILE1=$2
./c_program "$FLAG" "$FILE1" | other_c_program    # `< file2' is implicit

Also, it's a good idea to quote variable expansions. That way if $FILE1 contains whitespace or other tricky characters the script will still work.

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

1 Comment

Weird. First few time I did this I got a seg fault...then it started working fine. Thanks! Just need to iron out a few problems in my c code I guess
1

There is no simple way to do what you are asking. This is because when you run this:

$ ./script.sh -flag file1 < file2

The shell which interprets the command will open file2 for reading and pipe its contents to script.sh. Your script will never know what the file's name was, therefore cannot store that name as a variable. However, you could invoke your script this way:

$ ./script.sh -flag file1 file2

Then it is quite straightforward--you already know how to get file1, and file2 is the same.

2 Comments

Is there some way I can pipe file2 from the script into ./c_program then? Unfortunately I have to have < file2.
Absolutely: just do nothing and c_program will read from stdin. Do not do < file2 within your script--just say ./c_program -flag file1 | other_c_program. This is what @JohnKugelman's answer says too.

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.