The pure bash way with parameter expansion to substitute all spaces with underscores:
Mind that "$@" joins all arguments to the script with single spaces. This is likely not what you want. Say you have a file called
hello world.c
, calling your script as
myscript hello world.c
will do as you expect. But if for some reason there are not one but two spaces between "hello" and "world.c", your script will fail. You could fix this by quoting or escaping the filename, like
myscript "hello world.c"
or "
myscript hello\ \ world.c
, but be mindful that this makes it look like you could pass multiple filenames to the script like
myscript "hello world.c" "foo bar.c" "hoity toity.c"
but that will of course also not work (because ${@} merges all arguments into one string).
Anyway, while Bash manual says you can use character classes in parameter expansion substitution—that doesn't work here. So I can't use
mv "$@" "${@//[:space:]/_}"
to catch all types of whitespace (space, tab, newline; whitespace characters that could also be in filenames and you'd want to have replaced by underscores).
With tr that does work. Here's the same as above with tr but with using character class to catch all whitespace:
Code: Select all
#!/bin/bash
mv "$@" "$(echo -n "$@" | tr '[:space:]' '_')"