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

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.


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; 
    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

Disable browser 'Save Password' functionality

security browser autocomplete passwords

One of the joys of working for a government healthcare agency is having to deal with all of the paranoia around dealing with PHI (Protected Health Information). Don't get me wrong, I'm all for doing

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.