Timolution
Timolution

Reputation: 1

Trying to run a function in the Bash shell gives unexpected results

I have been trying to batch convert a bunch of really old MS office files to odf formats for archival purposes, using libreoffice from the command line. For this purpose I first gather all the files in a single directory and then invoke the following command (for doc files) within said directory:

/path/to/soffice --headless --convert-to odt *doc

This works well, and the command results in all doc files within the directory being converted in one go. I want to however avoid having to always type out the path to soffice with the necessary parameters, so I added the following to my Bash profile:

alias libreconv='function _libreconv(){ /path/to/soffice --headless --convert-to "$1" "$2"; }; _libreconv'

However, when I now try to invoke the following:

libreconv odt *doc

this results in only the first doc file in the directory being converted, after which the the function exits and returns me to prompt... Maybe I am missing something obvious (I am a cli newb after all), but I do not understand why invoking the function results in only the first file being converted versus all files when I run the soffice command directly.

Thanks in advance for any aid helping me understand what is going wrong here. :)

Upvotes: 0

Views: 60

Answers (1)

tripleee
tripleee

Reputation: 189749

Because your function only accepts two parameters.

Probably don't hardcode the path to soffice; instead, make sure your PATH includes the directory where it's installed.

The alias is completely useless here anyway; see also Why would I create an alias which creates a function?

If you wanted to create a function, try something like

libreconv () { soffice --headless --convert-to "$@"; }

The arguments "$1" and "$2" literally expand to the first two arguments. The argument "$@" expands to all the arguments, with quoting preserved (this is important if you want to handle file names with spaces in them etc; you see many scripts which incorrectly use "$*" or $@ without the quotes).

Tangentially, if soffice is in a weird place which you don't want in your PATH, add a symlink to it in a directory which is in your PATH. A common arrangement is to have ~/bin and populate it with symlinks to odd binaries, including perhaps scripts of your own which are installed for development in a Git working directory somewhere.

A common incantation to have in your .bash_profile or similar is

if [[ -d ~/bin ]]; then
    case :$PATH: in
     *:~/bin:* | *:$HOME/bin:* ) ;;
     *) PATH=~/bin:$PATH;;
    esac
fi

With that, you can (create ~/bin if it doesn't exist; mkdir ~/bin) and ln -s /path/to/soffice ~/bin to create a symlink to the real location.

Upvotes: 2

Related Questions