BASH script - execute command with variable and store result

I don't know how execute a command with variable and get result of this. I have many .h and .c files and I need convert each from ISO-8859 to UTF-8.

So I make:

ls | grep "\.[ch]" | xargs myscript.sh

And in my script in variable $1 is the filename. Now I need to perform

iconv -f ISO-8859 -t UTF-8 $1

and store result of this, because iconv print to stdout.

result=`iconv -f ISO-8859 -t UTF-8 $1`

echo $result 

This seems to be not working, because it give me some mismatch instead of converted $1.

Answers


If you need to do some kind of transformation on the data first, you can "capture" output with the following syntax:

result="$(iconv -f ISO-8859 -t UTF-8 $1)"

There is a gotcha here as well: if you are going to be storing large amounts of data with potential whitespace or other meddlesome characters in it, be sure to always quote the variable ("$result" instead of $result) to ensure it gets treated as a single string.


I'd do as such:

while read filename; 
do
    mv "$filename" "$filename.bck" && \
        iconv -f ISO-8859 -t UTF-8 "$filename.bck" > "$filename"
done < find -iname '*.[hc]'

This creates backups on the fly and also handles files with whitespace (not newline characters).


Here is a solution that even handles newlines:

find -name '*.[ch]' \
    -exec mv '{}' '{}.backup' \; \
    -exec iconv -f ISO-8859 -t UTF-8 '{}.backup' -o '{}' \;

Generally, NEVER parse filenames if you are going to use the results. The only sane ways I know of are

  1. Use shell globs, e.g. for file in ./*.[ch] ; do echo "$file" ; done. Only works for one directory.
  2. Use find in combination with -exec
  3. Use find in combination with -print0 (which prints the filenames as \0-separated strings) and use the output to build commandlines with xargs -0 and probably a helper script. This is quite cumbersome, though.

Also, make sure that relative filenames you use are prefixed with ./. Calling mv -from -to isn't safe, but mv ./-from ./-to is, and does what you want. E.g. when globbing, go with ./*.c rather than *.c.


Need Your Help

Videos inside tabs play at the same time in IE

jquery-ui jquery-ui-tabs

I am working with 7 tabs and there is a #container where the content goes! so far so good!

Why is Tomcat complaining about attempting to write too much to a response header?

java apache http tomcat http-headers

My service functions as a proxy server that will send GET requests using a proxy, add some info into the header, and return this to the client. But sometimes I get this error when I'm writing the e...