A bit of context, this question is a follow-up of this one: Bash remote autocompletion : change the 'starting' directory
Anyway, I'm writing my custom autocompletion bash script: I want the autocompletion to work just like cd
does, except that I want to get the names from a specific directory, not necessarily the current one. It works great except when filenames have spaces in them.
A quick example. Let's say the directory I'm getting the names from has two files in it: a_file
and another file
(notice the space). This happens:
my_command
TABTAB
a_file
file
another
The presentation isn't perfect but the idea is that I'm prompted with 3 choices, another file
being split in another
and file
. The desired output would be:
file_1
another file
. I would also like spaces to be escaped automatically:
my_command ano
TAB
my_command another\ file
Here's what my script looks like:
#!/bin/bash _get_file_list() { dir="/some/path/" cd $dir find * -maxdepth 0 } _GetOptMyCommand() { local cur COMPREPLY=() cur=${COMP_WORDS[COMP_CWORD]} case "$cur" in -*) COMPREPLY=( $( compgen -W "-h -l --help --list --" -- "$cur" ) );; *) COMPREPLY=( $( compgen -W "$(_get_file_list)" -- "$cur" ) );; esac return 0 } complete -F _GetOptMyCommand my_command
How do I deal with spaces in filenames and make my autocompletion script like cd
?
local IFS=$'\n'
seems to be what you're looking for. It's what worked for me.