简体   繁体   中英

How to pass a file as an argument to a bash script function?

I am trying to write a script to edit files within a function of a script, and save them as new files, using the name of the file passed as an argument to name the new file. This is an example of what i have:

renamer () {

temp="$1"
echo a test >> temp
cat $temp > new.$1

 }

echo this is > b

renamer b

I want a file named new.b which contains "this is a test" in it, but my file just has "this is" in it. Am I missing something here?

As others have said, to get the value of a variable you need to prefix the variable name with the unary operator $ . Try to be consistent with your quoting (if in doubt, quote it), and indent code inside functions (and if , while loops, etc.) all experienced programmers do that.

renamer () {

    # Indenting makes the code easier to read
    # copying positional parameters to a named parameter (variable)
    # is a good thing, but be consistent 

    temp="$1"

    # Adding quotes preserves additional whitespace in the text
    # and preserves whitespace in the filename
    echo "a test" >> "$temp"

    # Probably better to use cp(1)
    # You used $temp before, so why not here too?
    # Should this copy be done first?  See the comment by @tripleee
    cp "$temp" "new.$temp"

 }

# Preserve additional whitespace in the text by quoting
echo "this is" > b

renamer b

You might reasonably say that what I suggest is more work, but coding discipline will pay dividends later when you are dealing with larger and more complex scripts.

You are missing a dollar sign in front of temp

echo a test >> $temp

Without the dollar sign, bash is interpreting the string "temp" literally and not as a variable

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM