date int64 1,220B 1,719B | question_description stringlengths 28 29.9k | accepted_answer stringlengths 12 26.4k | question_title stringlengths 14 159 |
|---|---|---|---|
1,297,916,768,000 |
I regularly ssh on several different servers, some of which don't have fish installed, but many do. I'd like to get fish as shell if available (changing midway is always tedious, and you lose the history of what you already typed), but changing the default shell is not a good idea, as:
there are many different machines that I would need to change;
on many other I'm logged in through LDAP, and changing my shell as stored on LDAP would break on machines where fish is not available;
in general, as fish is not POSIX-sh compatible putting it as default shell may break commands executed by scripts through ssh;
finally, there are a few machines where the user is shared with other people (or, where I have to login another user), so changing the default shell is not a good idea.
So, ideally I'd like to have a command like ssh that automagically starts fish if available, or just leave whatever default shell is provided otherwise.
|
After some experiments, I put together the fissh script:
#!/bin/sh
ssh "$@" -t "sh -c 'if which fish >/dev/null ; then exec fish -li; else exec \$SHELL -li; fi'"
"$@" forwards all arguments passed to ssh
-t forces the allocation of a tty (otherwise ssh defaults to no tty when a command is specified)
sh -c is required because we don't know what shell we may have on the other side - on my personal machines I do have fish as default shell, which would break on the different if syntax;
which fish succeeds if it finds an executable fish; in that case, it is exec-ed (asking for an interactive and login shell);
otherwise, we fall back to $SHELL, which is the default shell for the current user ($ is escaped otherwise it gets expanded by sh "on this side").
-li is passed in either case, to make sure that we actually get a login interactive shell. While -i is mandated by POSIX for any shell, -l is "just" a common extension, but not putting it in is likely to result in bad surprises.
Notice that stdout of which is hidden (as in the normal case we don't care about where fish was found), but stderr (where the error message that fish couldn't be found) is intentionally left intact as a warning to the user that, despite our best intentions, fish couldn't be found.
To complete the experience, on my machines with fish I add the support for customized completion by creating a ~/.config/fish/completions/fissh.fish file containing
complete -c fissh -w ssh
to instruct fish that fissh has the exact same valid completions as ssh.
| How to use fish on remote servers that have it installed without changing login shell? |
1,297,916,768,000 |
I'm trying to test in a fish shell script for the existence of the figlet binary. Since I use Linux and OS X I cannot rely on the file being in the same location and need to resolve it dynamically. I'm used to doing this with $(which) in bash, which works.
With fish though this does not work properly. Why?
function print_hostname --description 'print hostname'
if test -x (which figlet)
hostname | figlet
end
end
|
Use type in fish like in Bourne-like shell:
if type -q figlet
hostname | figlet
end
Or to limit to executables in $PATH (ignoring functions, builtins):
if command -s figlet > /dev/null
hostname | figlet
end
See also Why not use “which”? What to use then?
| Fish shell testing for existence of file in $PATH |
1,297,916,768,000 |
I am working on my fish.config for using the fish shell.
I am trying to compare strings using bash syntax but fish doesn't accept the syntax. There is clearly another way to do it. Any suggestions for a solution as clean as the bash solution below?
if [[ $STRING == *"other_string"* ]]; then
echo "It contains the string!"
fi
|
It looks to me like there's a string function for that purpose:
$ set STRING something here
$ string match -q "other_string" $STRING; and echo yes
$ set STRING some other_string here
$ string match -q "other_string" $STRING; and echo yes
yes
Or:
if string match -q "other_string" $STRING
echo it matches
else
echo is does not match
end
| Does one string contain another in fish shell? |
1,297,916,768,000 |
I would like to have Ubuntu's MOTD in the fish shell.
Ubuntu's default is as follows:
That is essentially what I would like to see when open up my terminal (terminator, which loads fishfish)
As far as I can make out (Based on the information here), the default shell executes pam_motd, which in turn executes a bunch of scripts from /etc/update-motd.d
I don't know how to do this in the fish shell with any confidence. I haven't been able to find any information by searching.
Cheers
|
Put this in your ~/.config/fish/config.fish:
function fish_greeting
status --is-login
if [ $status != 0 ]
cat /run/motd.dynamic
end
end
This will make sure that you don't get the double motd when logging in remotely.
| Get default ubuntu motd in fish shell |
1,297,916,768,000 |
As is, the code below is invalid, because the brackets can not be used like that. if we remove them, it runs fine, and outputs:
true
true
code:
#!/usr/bin/fish
if ( false ; and true ) ; or true
echo "true"
else
echo "false"
end
if false ; and ( true ; or true )
echo "true"
else
echo "false"
end
How to get the functionality indicated by the brackets?
desired output:
true
false
|
You can use begin and end for conditionals as well:
From fish tutorial:
For even more complex conditions, use begin and end to group parts of them.
For a simpler example, you can take a look at this answer from stackoverflow.
For your code, you just have to replace the ( with begin ; and the ) with ; end.
#!/usr/bin/fish
if begin ; false ; and true ; end ; or true
echo "true"
else
echo "false"
end
if false; and begin ; true ; or true ; end
echo "true"
else
echo "false"
end
| How to group multiple conditions in an if statement in fish |
1,297,916,768,000 |
I switched to fish shell and quite happy with it. I didn't get how can I handle booleans. I managed to write config.fish that executes tmux on ssh (see: How can I start tmux automatically in fish shell while connecting to remote server via ssh) connection but I'm not happy with code readability and want to learn more about fish shell (I've already read tutorial and looked through reference). I want code to look like that (I know that syntax isn't correct, I just want to show the idea):
set PPID (ps --pid %self -o ppid --no-headers)
if ps --pid $PPID | grep ssh
set attached (tmux has-session -t remote; and tmux attach-session -t remote)
if not attached
set created (tmux new-session -s remote; and kill %self)
end
if !\(test attached -o created\)
echo "tmux failed to start; using plain fish shell"
end
end
I know that I can store $statuses and compare them with test as integers but I think it's ugly and even more unreadable. So the problem is to reuse $statuses and use them in if and test.
How can I achieve something like this?
|
You can structure this as an if/else chain. It's possible (though unwieldy) to use begin/end to put a compound statement as an if condition:
if begin ; tmux has-session -t remote; and tmux attach-session -t remote; end
# We're attached!
else if begin; tmux new-session -s remote; and kill %self; end
# We created a new session
else
echo "tmux failed to start; using plain fish shell"
end
A nicer style is boolean modifiers. begin/end take the place of parenthesis:
begin
tmux has-session -t remote
and tmux attach-session -t remote
end
or begin
tmux new-session -s remote
and kill %self
end
or echo "tmux failed to start; using plain fish shell"
(The first begin/end is not strictly necessary, but improves clarity IMO.)
Factoring out functions is a third possibility:
function tmux_attach
tmux has-session -t remote
and tmux attach-session -t remote
end
function tmux_new_session
tmux new-session -s remote
and kill %self
end
tmux_attach
or tmux_new_session
or echo "tmux failed to start; using plain fish shell"
| How to use booleans in fish shell? |
1,297,916,768,000 |
When I write a command that does not exist in the fish shell (let's say l instead of ls), fish takes some time before responding that the command does not exist.
I don't know if it looks for package to install or something else, but it is a bit annoying and I need to hit Ctrl-C to avoid waiting a few seconds.
Is there a way to disable this "feature", whatever it is?
|
Since the other answer does not work anymore, I found another solution which consists of adding this function in config.fish:
function __fish_command_not_found_handler --on-event fish_command_not_found
echo "fish: Unknown command '$argv'"
end
| Fish shell slow to respond when command does not exist |
1,297,916,768,000 |
I am trying to alias an executable in a directory with a space in it. For example:
alias myfile="/home/ben/test case/myfile"
Now, this is not expanded the way I want (it thinks /home/ben/test is the executable). In bash you can add extra quotes:
alias myfile="'/home/ben/test case/myfile'"
Sadly, in fish this does not work. What should I do instead?
|
alias in fish is just a wrapper for function builtin, it existed for backward compatible with POSIX shell. alias in fish didn't work as POSIX alias.
If you want the equivalent of POSIX alias, you must use abbr, which was added in fish 2.2.0:
abbr -a myfile "'/home/ben/test case/myfile'"
or:
abbr -a myfile "/home/ben/test\ case/myfile"
| fish: whitespace in alias |
1,297,916,768,000 |
I'm trying to add the following bash scripts to fish, yet am having trouble getting the syntax in fish right. Here is the original script:
export MINION_INSTALL=$HOME/minion
export NOTES_HOME=$HOME/Notes
export INBOX=$NOTES_HOME/inbox
if [ -d "$MINION_INSTALL" ] ; then
export PATH="$MINION_INSTALL:$PATH"
fi
source $MINION_INSTALL/aliases_for_minion
And this is the aliases_for_minion file:
alias mn="minion"
alias icannotfind="minion --open --archive --full $@"
alias newnote="minion --new-note $@"
alias open="minion --open $@"
alias remind="minion --new-note --quick $@"
alias summary="minion --count inbox; minion --list --show-tags=False today; \
minion --count next; minion --count soon; minion --count someday"
The minion command works fine if I run fish after starting bash.
Any help would be greatly appreciated!
|
Here's some examples of what this would look like in fish:
set -x INBOX $NOTES_HOME/inbox
if [ -d "$MINION_INSTALL" ]
set -x PATH $MINION_INSTALL $PATH
end
Note the absence of the quotes, which is especially important in the line that sets PATH. Quoting it would collapse all of the paths in the list to a single entry, which is not what you want.
The aliases are valid in fish, except for the $@ at the end. fish has arguments as $argv, not $@, but more importantly, any arguments are implicitly appended to the alias command. So you can just write:
alias newnote="minion --new-note"
Then, for example, newnote foo bar will become minion --new-note foo bar
If you like, you can verify it with functions newnote, which will show you the function that the alias produced.
Hope that helps!
| Converting bash script to fish |
1,297,916,768,000 |
I just recently switched to the fish shell from bash and I am having trouble sourcing my dircolors template file to get custom colors to appear for certain file extensions.
In bash, I was sourcing a template from ~/.dircolors/dircolors.256dark. The dircolors.256dark template has different file types mapped to different colors. For example, when I use ls, all .wav files will appear in orange. This was being sourced in my ~/.bash_profile like so:
# uses dircolors template
eval $(gdircolors ~/.dircolors/dircolors.256dark)
# Aliases
alias ls='gls --color=auto'
However, fish doesn't really use an rc file but instead sources from a config.fish, file but the syntax for certain operations is different in fish.
I'm trying to figure out how I would be able to accomplish this in fish. I like being able to visually distinguish different file types by color so this could potentially be a deal breaker for me if there is no way of doing this in fish.
P.S.
For clarity, I am not trying to simply change the colors of directories or executable files, but files with different file extensions. For example if I did ls in a directory, I would get the following:
my_file.py # this file would be green for example
my_file.js # this file would be yellow
my_file.wav # this file would be orange
EDIT: I used homebrew on macOS for dircolors.
|
The solution was actually pretty simple. Within my ~/.config/fish/config.fish file, I just needed to drop the "$" from the eval statement. So it would look like this:
# uses dircolors template
eval (gdircolors ~/.dircolors/dircolors.256dark)
# Aliases
alias ls='gls --color=auto'
| Using ~/.dircolors in fish shell |
1,297,916,768,000 |
I switched from bash to fish shell. I liked it and decided to use it on my servers also. How can I start tmux automatically on ssh connection? I followed this instruction for bash but fish shell is different and this recipe doesn't work without cardinal rewriting.
|
Byobu, a terminal multiplexer, based on tmux, offers an autostart feature.
| How can I start tmux automatically in fish shell while connecting to remote server via ssh |
1,470,216,637,000 |
This is kind of a followup to another question.
I use a custom command in my gnome-terminal profile (/usr/bin/fish). When using Ubuntu 14.04 a Ctrl-Shift-N opened a new gnome-terminal window in the same directory as the current terminal. With 16.04 this changed and now it always opens in $HOME. I want the old behavior.
This has nothing to do with sourcing /etc/profile.d/vte.sh. Fish does this correctly as I can observe directory changes in the title bar. If I uncheck the custom command box in my gnome-terminal profile, the new terminal window correctly uses the current directory. However, it use my system default shell: bash.
I cannot change my system shell (chsh), because this is shared across other machines, where fish is not available.
I don't see a way to fix this from fish, since the terminals current directory is not available.
Edit: Since this a regression in Ubuntu, I also reported this as #1609342 to Ubuntu.
|
As Gilles mentioned in a comment, setting the SHELL variable works as well. It does not have downside of my other answer. Here are the details:
Create .xsessionrc in your home directory with contents:
SHELL=/usr/bin/fish
Disable custom command in gnome-terminal profile options.
Log out and in again.
Gnome-terminal should respect the variable and use that custom command. It does for me on Ubuntu 16.04.1 and solves the working directory problem.
| Gnome-terminal custom command and dynamic working directory |
1,470,216,637,000 |
Readline and therefore Bash have a very useful command called operate-and-get-next, bound by default to Ctrl-O, that executes the current line, after selecting it from the history, and advances the history pointer by one, instead of clearing the command line prompt, as Enter would do.
So if you wish to repeat a number of sequential commands you did recently, one by one in the same order, you can:
recall the first command in the sequence from the history
execute it with Ctrl-O
check the output
check that the commandline is now pointing to the next command in the sequence
GOTO 2.
Does Fish have anything like this, or can it be implemented as a function?
|
Fish does not have the concept of a "history pointer", which points at the currently selected history entry, so the answer is: No.
| Fish equivalent of Bash / readline's Ctrl-O "operate-and-get-next" |
1,470,216,637,000 |
I have recently moved to fish from bash. I'm immediately in love with the out-of-the-box functionality, but I'm a little bit at a loss when it comes to configuring the shell.
I've read through the documentation, particularly the section about initialization, and it states:
On startup, Fish evaluates a number of configuration files...
Configuration snippets in files ending in .fish, in the directories:
$__fish_config_dir/conf.d (by default, ~/.config/fish/conf.d/)
...
User initialization, usually in ~/.config/fish/config.fish ...
So far, this is clear to understand. Coming from bash, I took my .bash_globals and .bash_aliases files, rewrote them a little bit according to fish's syntax, placed them into the ~/.config/fish/conf.d/ and they are loaded as expected.
However, when I looked over the contents of the config.fish file, I couldn't figure out anything that would need to be put there. To my understanding, fish is designed to work already out of the box, so the usual bash config like setting HISTCONTROL isn't necessary. Nor are the conf.d/ files called from some main script (like the .bash_aliases, etc., would be in .bashrc) - they're loaded automatically.
Is there some particular use case where config.fish is preferred - or even required - over conf.d/ files? So far, I would say individual files are cleaner to read, maintain and move between hosts. Is there some convention that's recommended to follow? Was there a specific motivation behind allowing so many levels of config, aside from giving users more freedom?
|
As far as purpose, I'd say there are several good reasons to support both.
First, and probably most importantly, as @Zanchey points out in the comments, conf.d support came about in release 2.3.0, so getting rid of config.fish at that point would have been a breaking change.
Second, as you said, freedom for the users to choose the way they would like to handle startup behavior.
Next, it's also somewhat "path of least resistance". I definitely share your preference for the modularity of conf.d/ files, and I love not having a config.fish myself. But some (perhaps even most) users who are moving over to fish for the first time default to the familiarity of a single .bash_profile-like place to put their config. I can imagine that the paradigm shift of not having a single-file config might be off-putting to some. In other words, config.fish helps provide a smooth migration for new users.
Further, config.fish is easier to explain to a new user, since it maps to something they already know in their previous shell. Even the fish FAQ defaults to telling users that config.fish is the equivalent of their previous startup scripts. Although I do wish they'd go on to explain the conf.d/ alternative as well there.
And config.fish does have one other small advantage, in that the execution order is more explicit (i.e. it's executed start to end). conf.d/ files are read just like any other conf.d/, in alphabetical order (or glob-result order, most likely). In my experience, this means that you have to resort to 00_dependency.fish type of naming to ensure that one file is run before others. That said, it should rare that anyone would have to resort to that.
As for "convention", well, I know many distributions set up their configuration files (e.g. the Apache2 httpd.conf) with a default "single-file" that goes on to process a conf.d/ structure. In fish's case, they just did away with the boilerplate for conffile in ~/.config/fish/conf.d/*.fish; source $conffile; end that would otherwise be required in config.fish.
| What is the purpose of (and possibly the convention of using) multiple locations for user configuration in fish shell |
1,470,216,637,000 |
In the zsh shell, I can write something into the command line history like so:
#!/bin/zsh
cmd="cd /special/dir"
print -s $cmd" # save command in history for reuse
How may I do that in the fish shell?
|
AFAICT, only the read builtin and the shell command line reader can add entry to the history, but only when stdin is a tty device, so that's not easily scriptable.
But you could add the entry by hand with something like:
function add_history_entry
begin
flock 1
and echo -- '- cmd:' (
string replace -- \n \\n (string join ' ' $argv) | string replace \\ \\\\
)
and date +' when: %s'
end >> $__fish_user_data_dir/fish_history
and history merge
end
And then:
add_history_entry 'cd /special/dir'
That works for me with fish 3.1.2 here, but note that fish is a bit of a moving target with API changing often in incompatible ways between one version and the next. That __fish_user_data_dir and the format of the history file are not documented, so they might go away/change in a future version. The above also assumes the $fish_history variable is not set to anything other than fish.
| How to write a command to history in fish shell? |
1,470,216,637,000 |
I decided to try fish shell, and I'm having trouble with some aliases. So I guess the painless way of doing the things would be executing the bash commands inside fish shell functions. Something like that :
function fish_function
start bash
... bash commands ...
stop bash
end
Is that possible?
e.g: the command
pacman -Qtdq && sudo pacman -Rns $(pacman -Qtdq)
doesn't work in fish shell and I have no idea how to convert this
|
Apparently fish uses ; and for && and () for command substitutions.
So just changing the command to
pacman -Qtdq; and sudo pacman -Rns (pacman -Qtdq)
should work.
Answering the actual question, normally you can get a statement to be executed in Bash simply by redirecting the statement to a bash command's STDIN by any mean (notice that I'm on Zsh, which supports here strings, and that the statement prints the content of a Bash-specific variable):
% <<<'echo $BASH' bash
/bin/bash
However as a general rule I'd suggest to use bash's -c option. For example here strings and pipes don't play too well with multiple commands, here documents will be expanded by the current shell, etc (nevertheless those need to be supported by the current shell).
Overall bash -c seems to be always a safe bet:
bash -c 'pacman -Qtdq && sudo pacman -Rns $(pacman -Qtdq)'
Which for multiple commands becomes something like this:
bash -c '
command1
command2
command3
'
| Execute bash command inside fish function |
1,470,216,637,000 |
This is Bash. The behavior is similar in fish.
$ which python
/usr/bin/python
$ alias py=python
$ type py
py is aliased to `python'
And then, running type -P py prints nothing, where as I expected to print /usr/bin/pyton in a similar fashion to what is seen below.
$ type ls
ls is aliased to `ls --color=auto'
$ type -P ls
/bin/ls
The documentation for the -P option reads
-P force a PATH search for each NAME, even if it is an alias,
builtin, or function, and returns the name of the disk file
that would be executed
I've confirmed that /usr/bin (the directory where python is located) is in PATH.
What is going on here?
|
This:
force a PATH search for each NAME, even if it is an alias,
does not mean that bash will expand the alias and then search for the expanded command. It means that, if there were a command foo, and also an alias foo, the type -P foo will still look for the command named foo, even though there's an alias masking it. So bash isn't expanding py in type -P py to be python, and it won't show /usr/bin/python.
| Issue with type force PATH search |
1,470,216,637,000 |
I ran into an issue trying to dynamically set some variables based on output of a program, in a fish function.
I narrowed my issues down to a MWE:
function example
eval (echo 'set -x FOO 1;')
end
calling:
>example
>echo $FOO
results in no output -- ie the FOO environment variable has not been set.
How should I have done this?
|
The same thing happens in a simpler form:
function trythis
set -x foo bar
end
If you now run trythis and echo $foo, it is not set either. That's because fish's -x by itself doesn't change the scope of the variable, which is by default local to the function unless it exists globally or universally already.
Try:
eval (echo 'set -gx FOO 1;')
Where the g is for global. This makes the variable work like a normal POSIX exported value. It's interesting that it works the same way with eval as it would with just plain set; if you use that line sans g straight on the command line, $FOO is set, so eval and process substitution () have not introduced a new scope or subshell, and when executed that way within a function, the scope of the function applies.
| Why doesn't set -x work within eval within a function in fish? |
1,470,216,637,000 |
I want to define a function, and call that function every n seconds. As an example:
function h
echo hello
end
Calling h works:
david@f5 ~> h
hello
But when using watch, it doesn't...
watch -n 60 "h"
...and I get:
Every 60.0s: h f5: Wed Oct 10 21:04:15 2018
sh: 1: h: not found
How can I run watch in fish, with the function I've just defined?
|
Another way would be to save the function, then ask watch to invoke fish:
bash$ fish
fish$ function h
echo hello
end
fish$ funcsave h
fish-or-bash$ watch -n 60 "fish -c h"
funcsave saves the named function definition into a file in the path ~/.config/fish/functions/, so ~/.config/fish/function/h.fish in the above case.
| Define function in fish, use it with watch |
1,470,216,637,000 |
In fish, when I type history | less I see the following for example:
history | less
export HISTTIMEFORMAT="%h/%d - %H:%M:%S "
bash
in bash I see this:
491 18/04/16 14:31:02 cd
492 18/04/16 14:31:02 ls -l
493 18/04/16 14:31:02 less .bashrc
so I can execute the command again with !491 for example and I also can do an audit on my server, but fish doesn't have a way to display this.
I also tried to add the time and date with export HISTTIMEFORMAT="%h/%d - %H:%M:%S " but nothing, any ideas on how to add that like in bash?
|
fish tracks but does not yet surface the history timestamps. See issue #677 - there's some contributed scripts in there to parse the history file.
fish does not support exclamation mark history expansion, because the syntax is hard to remember and it's often invoked by mistake. You can follow the discussion in #288. What you normally do is to start typing the command, and accept the autosuggestion when it appears (right-arrow or ctrl-F). Another option is to type part of the command and use the up arrow to cycle through matching history items.
| Why there isn't a number of the command and a timestamp for fish? |
1,470,216,637,000 |
Is it possible to set environment variables with export in Fish Shell? I am working on a project that configures variables this way and it does not make sense to maintain a separate configuration file just for fish.
Consider this example in bash:
echo -e "foo=1\nfoobar=2\n" > foo; export $(cat foo | xargs); env | grep foo
foo=1
foobar=2
In fish shell, it appears that it will only set a single variable, and only if there is one variable in the file:
~ $ echo -e "foo=3\nfoobar=4" > foo; export (cat foo | xargs); env | grep foo
~ $ echo -e "foo=3" > foo; export (cat foo | xargs); env | grep foo
foo=3
Is this just a flaw / omission in the Fish implementation of export?
This question is similar to but different from these other two posts:
Share environment variables between bash and fish
how to set and use multiple parameters in single environmental variable in fish shell
|
Your example almost works perfectly - it's not export that's the problem, but the use of xargs.
Try:
echo -e "foo=3\nfoobar=4" > .env; export (cat .env); env | grep foo
The reason is that a command substitution separates arguments on newlines, and xargs removes them:
> count (cat .env | xargs)
1
> count (cat .env)
2
| Fish Shell: How to set multiple environment variables from a file using export |
1,470,216,637,000 |
I want to check a condition if a variable is null in fish(friendly interactive shell).
if test "$argv" = null
# do something...
else
# do something else...
|
I don't know "fish" specifically, but I do know the standard "test".
Try:
test "$argv" = ""
or
test "x$argv" = x
or
test -z "$argv"
This assumes you are wanting to test for it being unset or empty.
If you only want one of those two cases, you will need shell specific variable expansion modifiers.
Note that the second sample is often found in code trying for high portability.
It avoids having empty parameters, as they seem to get lost at times.
The third sample is the test option to test for an empty string.
| check if variable is null in fish |
1,470,216,637,000 |
I often start a long running command that is bound to either CPU, Disk, RAM or Internet connection. While that is running, I find that I want to run a similar command. Let's say downloading something big.
Then I start a shell with wget ...1 and let it run. I could open another shell and run the other wget ...2, but now they would fight for the bandwidth. When I just type the second command into the running shell, it will execute that later on, since wget is not interactive.
Is there a reasonable way to do this with either Bash or Fish Shell?
|
If you have already running wget http://first in foreground you can pause it with CTRL+z and then return it back to work with another command right after it:
fg ; wget http://second
It should work in most cases.
If that way is not acceptable, you should go with lockfile. Or even just to monitor the process via ps (lockfile is better).
| Queue a task in a running shell |
1,470,216,637,000 |
I'm trying to set the fish history pager to be bat -l fish for syntax highlighting.
(i.e. set the PAGER environment variable bat -l fish just for the history command).
I tried:
# 1:
alias history "PAGER='bat -l fish' history"
# results in "The function “history” calls itself immediately, which would result in an infinite loop"
# 2:
alias history "PAGER='bat -l fish' \history"
# results in the same.
# 3:
alias _old_history history
alias history "PAGER='bat -l fish' _old_history"
# results in (line 1): The call stack limit has been exceeded
I'm aware that abbr works in this case, but this changes my history command, and this is not what I want.
|
Two things are happening here:
fish's alias actually creates a function.
fish ships with a default history function already.
So when you write
alias history "PAGER='bat -l fish' history"
what you actually have is the recursive function
function history
PAGER='bat -l fish' history $argv
end
Some solutions:
use a different name for your alias
alias hist 'PAGER="bat -l fish" history'
Don't alias _old_history hist, but copy it instead
functions --copy history _old_history
alias history 'PAGER="bat -l fish" _old_history'
If you don't care to keep fish's function, invoke the builtin history command in your own function
function history
builtin history $argv | bat -l fish
end
why doesn't the builtin history support pager?
I assume the fish designers didn't think that was a core part of the history functionality. I assume they put the user-facing stuff in a function that users can override.
Here's the relevant snippet from the default history function:
case search # search the interactive command history
test -z "$search_mode"
and set search_mode --contains
if isatty stdout
set -l pager (__fish_anypager)
and isatty stdout
or set pager cat
# If the user hasn't preconfigured less with the $LESS environment variable,
# we do so to have it behave like cat if output fits on one screen.
if not set -qx LESS
set -x LESS --quit-if-one-screen
# Also set --no-init for less < v530, see #8157.
if type -q less; and test (less --version | string match -r 'less (\d+)')[2] -lt 530 2>/dev/null
set -x LESS $LESS --no-init
end
end
not set -qx LV # ask the pager lv not to strip colors
and set -x LV -c
builtin history search $search_mode $show_time $max_count $_flag_case_sensitive $_flag_reverse $_flag_null -- $argv | $pager
else
builtin history search $search_mode $show_time $max_count $_flag_case_sensitive $_flag_reverse $_flag_null -- $argv
end
| how to alias the `history` function in fish shell |
1,470,216,637,000 |
if you
curl https://www.toptal.com/developers/gitignore/api/python
you see the file as expected, with newlines. But if I
set response (curl https://www.toptal.com/developers/gitignore/api/python)
echo $response
in fish the newlines are gone. I've looked at fish read but
url $gitignoreurlbase/python | read response # I have also tried read -d 'blah'
echo $response
just shows a blank.
How do I capture the multi-line output?
|
Replace set var (command) with set var (command | string split0)
Explanation:
command substition splits on newlines by default. The $response variable is a list of lines of the output. This is documented
$ set var (seq 10)
$ set --show var
$var: not set in local scope
$var: set in global scope, unexported, with 10 elements
$var[1]: length=1 value=|1|
$var[2]: length=1 value=|2|
$var[3]: length=1 value=|3|
$var[4]: length=1 value=|4|
$var[5]: length=1 value=|5|
$var[6]: length=1 value=|6|
$var[7]: length=1 value=|7|
$var[8]: length=1 value=|8|
$var[9]: length=1 value=|9|
$var[10]: length=2 value=|10|
$var: not set in universal scope
Fortunately so is the remedy
$ set var (seq 10 | string split0)
$ set -S var
$var: not set in local scope
$var: set in global scope, unexported, with 1 elements
$var[1]: length=21 value=|1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n|
$var: not set in universal scope
# OR
$ set oldIFS $IFS
$ set --erase IFS
$ set var (seq 10)
$ set -S var
$var: not set in local scope
$var: set in global scope, unexported, with 1 elements
$var[1]: length=20 value=|1\n2\n3\n4\n5\n6\n7\n8\n9\n10|
$var: not set in universal scope
$ set IFS $oldIFS
Note the difference with the string split0 keeping the trailing newline.
If you're OK with $response being a list of lines, but you just want to display it properly:
printf "%s\n" $response
# or, with just a literal newline as the join string
string join "
" $respose
| fish shell : capture multi-line output to a variable with piping or read |
1,470,216,637,000 |
I've been trying to learn to use jq and for bash it uses the <<< operator which I cannot understand after reading the bash documentation, what is this operator for?
Besides that, I use the fish shell instead. How can I translate jq . <<< '{"some": "xyz"}' (works in bash) to the fish shell?
|
The <<< operator is a here-string
3.6.7 Here Strings
Given:
[n]<<< word
The word undergoes brace expansion, tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, and quote removal. Pathname expansion and word splitting are not performed. The result is supplied as a single string, with a newline appended, to the command on its standard input (or file descriptor n if n is specified).
To translate this to fish shell you could likely do:
echo '{"some": "xyz"}' | jq
(which would work in bash as well)
| Bash operator translation to fish |
1,470,216,637,000 |
I'm using fish shell. Let's say that I have a directory named books, containing files title-1, title-2 and title-3:
$ tree books
books/
├── title-1
├── title-2
└── title-3
0 directories, 3 files
If I type git add boo and press tab, fish will automatically complete to git add books/title- . I can press tab multiple times to cycle through the files books/title-1, books/title-2 and books/title-3.
I would prefer it if fish completed to git add books/ instead, the way bash or zsh does it. I'm used to that way, and it's more convenient to run git add against a directory rather than a list of files. How can I configure fish to complete this way?
|
You don't.
Fish's git completions print the entire path and there is no configuration option to disable this.
You can press ctrl-w to delete back to the last "/".
| When pressing tab, how can I make fish complete to directory/ instead of directory/prefix? |
1,470,216,637,000 |
After doing an OS upgrade (opensuse leap 15.2 -> 15.3), my XDG setup broke. Among other things, my XDG_DATA_DIR env var uses two different value separators: : and .
Current XDG_DATA_DIRS value:
/home/bernard/.local/share/flatpak/exports/share:/var/lib/flatpak/exports/share:/usr/local/share:/usr/share:/var/lib/snapd/desktop /var/lib/snapd/desktop
When looking for the code that populates this variable, I came across scripts in /etc/profile.d/, but from debugging the snapd.sh one, it doesn't seem to be causing the deficiency. I modified snapd.sh and I printed the variable into a /tmp/var at the script start and script end. By observing the results it looks as if this script wasn't changing anything in XDG_DATA_DIRS.
snap version: 2.54.1
fish version: 3.3.1
|
I don't know about the dot: I think you'll have to dig into which process is adding that.
The last directory element separated by a space is telling though. It seems you're adding a directory to XDG_DATA_DIRS in fish and expecting subprocess to get a colon-separated value. fish does that automatically only for PATH variables.
In your fish config, try this before you do any manipulation of that variable:
set --path -x XDG_DATA_DIRS $XDG_DATA_DIRS
| XDG_DATA_DIRS env variable using two separator types in fish shell |
1,470,216,637,000 |
So I'm trying to change my fish shell terminal prompt but every time I change anything too complicated (beyond colour changes and rearranging the prompt), it just turns up blank.
I'm running Arch Linux.
I've tried lots of terminal emulators. termite, kitty, konsole, simple terminal, rxvt-u, terminology. None of the normal terminal emulators would show the prompt I'm expecting.
But there was one that worked, the terminal emulator inside visual studio code.
I've tried as many random different prompts I could get my hand on but all of them would just look blank everywhere except visual studio code.
Any idea how I can get the terminal prompt to look the way it should?
in short, it looks like this
When it should look like this
Heres the content of ~/.config/fish/functions/fish_prompt.fish
# name: sashimi
function fish_prompt
set -l last_status $status
set -l cyan (set_color -o cyan)
set -l yellow (set_color -o yellow)
set -g red (set_color -o red)
set -g blue (set_color -o blue)
set -l green (set_color -o green)
set -g normal (set_color normal)
set -l ahead (_git_ahead)
set -g whitespace ' '
if test $last_status = 0
set initial_indicator "$green◆"
set status_indicator "$normal❯$cyan❯$green❯"
else
set initial_indicator "$red✖ $last_status"
set status_indicator "$red❯$red❯$red❯"
end
set -l cwd $cyan(basename (prompt_pwd))
if [ (_git_branch_name) ]
if test (_git_branch_name) = 'master'
set -l git_branch (_git_branch_name)
set git_info "$normal git:($red$git_branch$normal)"
else
set -l git_branch (_git_branch_name)
set git_info "$normal git:($blue$git_branch$normal)"
end
if [ (_is_git_dirty) ]
set -l dirty "$yellow ✗"
set git_info "$git_info$dirty"
end
end
# Notify if a command took more than 5 minutes
if [ "$CMD_DURATION" -gt 300000 ]
echo The last command took (math "$CMD_DURATION/1000") seconds.
end
echo -n -s $initial_indicator $whitespace $cwd $git_info $whitespace $ahead $status_indicator $whitespace
end
function _git_ahead
set -l commits (command git rev-list --left-right '@{upstream}...HEAD' ^/dev/null)
if [ $status != 0 ]
return
end
set -l behind (count (for arg in $commits; echo $arg; end | grep '^<'))
set -l ahead (count (for arg in $commits; echo $arg; end | grep -v '^<'))
switch "$ahead $behind"
case '' # no upstream
case '0 0' # equal to upstream
return
case '* 0' # ahead of upstream
echo "$blue↑$normal_c$ahead$whitespace"
case '0 *' # behind upstream
echo "$red↓$normal_c$behind$whitespace"
case '*' # diverged from upstream
echo "$blue↑$normal$ahead $red↓$normal_c$behind$whitespace"
end
end
function _git_branch_name
echo (command git symbolic-ref HEAD ^/dev/null | sed -e 's|^refs/heads/||')
end
function _is_git_dirty
echo (command git status -s --ignore-submodules=dirty ^/dev/null)
end
|
This is a bug in fish triggered by using non-ASCII chars with a non-unicode capable locale.
Set your locale to something that can handle UTF-8 (i.e. not the default "C")
| Terminal fish prompt blank |
1,470,216,637,000 |
I have a bit complicated question. I am using Windows 10 Anniversary Update with Bash for Ubuntu. I am connecting to server via ssh. This server uses fish shell. And when I press arrows it just prints some symbols instead of showing me command history or guessing my next command. Here is what I see:
arrow up prints [A
arrow down prints [B
arrow right prints [C
arrow left prints [D
However, arrows works fine in bash. Is there any ideas why it is happening?
|
The Windows 10 Anniversary Update with Bash for Ubuntu is essentially running bash in a console window, whose escape sequences (including input such as arrow keys) are documented in MSDN:
Console Virtual Terminal Sequences
By itself, ssh is largely irrelevant (it passes characters to/from the remote machine unchanged). What matters is the terminal description that your remote machine uses and whether the fish shell initializes things.
Given that you are seeing [A on the remote machine, that says your terminal is sending normal-mode cursor keys (the state when things are not initialized). That's consistent with bash, whose configurations tend to be either hardcoded (look at most .inputrc files) or based on the non-initializing "linux" terminal description. On the Windows side, sure: bash will "work", because it's configured to work with what's there. On the remote side, the fish shell uses whatever is in TERM (which likely is "xterm"). If it's "xterm", then the fish shell would be expecting application mode cursor sequences, e.g., ^[OA versus ^[[A, and seeing the latter would mishandle it.
Further reading:
Special keys (xterm manual)
Why can't I use the cursor keys in (whatever) shell? (xterm FAQ)
| Windows bash takes arrows as symbols via ssh and fish shell on server |
1,470,216,637,000 |
this is my fish configuration:
set -x CGO_CPPFLAGS 'llvm-config --cppflags'
set -x CGO_LDFLAGS 'llvm-config --ldflags --libs --system-libs all'
set -x CGO_CXXFLAGS '-std=c++11'
I've tried running make on my LLVM-based project, but I get the following error:
clang: error: unsupported option '--cppflags'
clang: error: no such file or directory: 'llvm-config'
make: *** [all] Error 2
Is this an error in my configuration file? If so, what am I doing wrong?
|
Try setting the variables to the output of llvm-config using command substitutions, rather than the raw commands themselves:
set -x CGO_CPPFLAGS (llvm-config --cppflags | tr -s ' ' \n)
set -x CGO_LDFLAGS (llvm-config --ldflags --libs --system-libs all | tr -s ' ' \n)
set -x CGO_CXXFLAGS '-std=c++11'
The pipe through tr is to avoid getting bitten by a difference in behaviour between bash/zsh and fish.
| Can't seem to set environmental variables in fish correctly? |
1,470,216,637,000 |
I've been using terminator, and recently started using fish. When terminator starts (bash) I can use, for example, node just fine. If I then start fish I can still run node just fine.
I set terminator to "Run a custom command instead of my shell", in this case fish, but then I can no longer just run node. Terminal says it is not installed. I kinda can see what the problem is... If I run fish from bash everything just works... It makes sense, I am guessing...
How can I start fish automatically but have the bash stuff working already?
(It's clear I'm not sure what I'm talking about and that is perhaps why I could not find a solution via google...)
|
Given your description of the symptoms, you've evidently installed node in a location which is not on your system's default command search path. There's nothing wrong with that, you just need to add that location to the PATH environment variable. That's what you did wrong: you did that in the wrong file.
Unfortunately, a lot of tutorials tell you to set PATH in .bashrc. This is wrong, as you've noticed: if you do that then the setting is only available if you start programs via an interactive instance of bash. Generally speaking, don't set environment variables in .bashrc. Instead, set environment variables in a file that is loaded as part of your session startup when you log in, such as ~/.profile. See Is there a ".bashrc" equivalent file read by all shells? and How to permanently set environmental variables
So the solution is to remove the PATH changes that you've added to ~/.bashrc (either manually or by running some installation script) and put those lines in ~/.profile instead.
To make the changes take effect in your current session, you need to change the environment in your window manager. This will affect any future terminal started from the window manager (there's no way to affect existing terminals). How to do that depends on the window manager.
| Start bash then autostart fish with terminator |
1,470,216,637,000 |
I gather that bash has a "magic space" function, where if I do e.g. sudo !!<space> it will blow in sudo ./my_last_command. Does something similar exist in fish?
|
From the FAQ in the source (I can't find any documentation online):
Why doesn't history
substitution ("!$" etc.) work?
Because history substitution is an
awkward interface that was invented
before interactive line editing was
even possible. Fish drops it in favor
of perfecting the interactive history
recall interface. Switching requires
a small change of habits: if you want
to modify an old line/word, first
recall it, then edit. E.g. don't type
"sudo !!" - first press Up, then Home,
then type "sudo ".
| Does Fish have a "magic space"? |
1,470,216,637,000 |
I am trying to write some completions for an in-house tool. We'll call it thetool.
Lots of the commands to thetool do not take a 'file' as an argument. I thought that --no-files and/or --exclusive would do this for me but I don't seem to be able to get it to work.
In other words how can I write completions so that the following command does show files in the tab completion
$ thetool file-command *hit-tab*
while the following command does NOT show files in the tab completion
$ thetool non-file-command *hit-tab*
Let's try for a toy example:
$ function thetool
echo $argv
end
$ complete --command thetool --no-files --condition "not __fish_seen_subcommand_from file-command non-file-command" --arguments "file-command" --description "file-command"
$ complete --command thetool --no-files --condition "not __fish_seen_subcommand_from file-command non-file-command" --arguments "non-file-command" --description "non-file-command"
$ complete --command thetool
complete --no-files thetool -d non-file-command -a non-file-command -n 'not __fish_seen_subcommand_from file-command non-file-command'
complete --no-files thetool -d file-command -a file-command -n 'not __fish_seen_subcommand_from file-command non-file-command'
now try the completions out:
$ thetool *hit-tab*
file-command (file-command) non-file-command (non-file-command)
Looks good so far...
$ thetool non-file-command *hit-tab*
bin/ dev.yml Judgment.lock README.md TODO.md
completion_test.fish exe/ lib/ shipit.production.yml vendor/
completion_test.zsh Gemfile linters/ sorbet/ zsh_completions.sh
coverage/ Gemfile.lock Rakefile test/
SEE! What are all those file suggestions doing there?!
Let's try again:
$ complete --command thetool --force-files --condition "not __fish_seen_subcommand_from file-command non-file-command" --arguments "file-command" --erase
$ complete --command thetool --force-files --condition "not __fish_seen_subcommand_from file-command non-file-command" --arguments "file-command"
$ complete --command thetool --no-files --condition "not __fish_seen_subcommand_from file-command non-file-command" --arguments "non-file-command"
$ complete --command thetool
complete --no-files thetool -a non-file-command -n 'not __fish_seen_subcommand_from file-command non-file-command'
complete --force-files thetool -a file-command -n 'not __fish_seen_subcommand_from file-command non-file-command'
$ thetool *hit-tab*
bin/ dev.yml Gemfile.lock non-file-command sorbet/ zsh_completions.sh
completion_test.fish exe/ Judgment.lock Rakefile test/
completion_test.zsh file-command lib/ README.md TODO.md
coverage/ Gemfile linters/ shipit.production.yml vendor/
arrrg can someone help me understand what is going on and what I'm doing wrong?
|
You have no call that ever tells fish to disable files if it has seen non-file-command.
Let's go through them:
complete --command thetool --no-files --condition "not __fish_seen_subcommand_from file-command non-file-command" --arguments "file-command" --description "file-command"
fish has seen non-file-command, the condition is false.
complete --command thetool --no-files --condition "not __fish_seen_subcommand_from file-command non-file-command" --arguments "non-file-command" --description "non-file-command"
fish has seen non-file-command, the condition is false.
complete --command thetool
This does nothing.
complete --no-files thetool -d non-file-command -a non-file-command -n 'not __fish_seen_subcommand_from file-command non-file-command'
fish has seen non-file-command, the condition is false.
complete --no-files thetool -d file-command -a file-command -n 'not __fish_seen_subcommand_from file-command non-file-command'
fish has seen non-file-command, the condition is false.
No condition where we'd disable files is true, so we default to enabling them. There is nothing that tells it to disable files if non-file-command was given.
Add
complete --command thetool --no-files --condition " __fish_seen_subcommand_from non-file-command"
and it'll work.
Or, if you have a lot of things that don't take files and just a few that do, you can add
complete --command thetool --no-files
which will disable files always (it has no condition so it's always true, as long as you're completing thetool), and then force-files for those cases that do, e.g.
complete --command thetool --condition "__fish_seen_subcommand_from file-command" --force-files
| Fish Completions - How to prevent file completions? |
1,470,216,637,000 |
I was trying to learn and write some fish scripts, but I encountered a strange issue.
# a.fish
# this is a fish script
set temp (getopt -o abc -l ace,bad,correct -- $argv)
echo $temp
When I ran fish ./a.fish -a -b --correct it worked fine and output
-a -b --correct --
However, when I changed the $argv to "$argv" and ran it again, I got this
Then I wrote a bash script
# a.sh
temp=$(getopt -o abc -l ace,bad,correct -- $@)
echo $temp
and ran it with bash ./a.sh -a -b --correct. Worked fine. After I added " around $@ it still worked fine!
So here comes the question:
What's the difference between $argv and $@ (or maybe I should ask whether fish and bash handle variables differently?)
I thought it was just simple replacement but this confused me. Can somebody help me? Any help will be appreciated :)
OS: ubuntu 16.04
|
Yes, different shells are different. strace as always can help show what exactly is sent through an execve(2) call.
$ cat fecho
/usr/bin/echo $argv
$ cat fechoquoted
/usr/bin/echo "$argv"
$ fish ./fecho a b c
a b c
$ fish ./fechoquoted a b c
a b c
$
Yet these two are actually rather different under the strace-scope:
$ strace -qq -f -e trace=execve fish ./fecho a b c
execve("/usr/bin/fish", ["fish", "./fecho", "a", "b", "c"], [/* 22 vars */]) = 0
[pid 15532] execve("/usr/bin/echo", ["/usr/bin/echo", "a", "b", "c"], [/* 21 vars */]) = 0
a b c
$ strace -qq -f -e trace=execve fish ./fechoquoted a b c
execve("/usr/bin/fish", ["fish", "./fechoquoted", "a", "b", "c"], [/* 22 vars */]) = 0
[pid 15542] execve("/usr/bin/echo", ["/usr/bin/echo", "a b c"], [/* 21 vars */]) = 0
a b c
$
The first passes a list of arguments to echo ("a", "b", "c"), and the second a single list item ("a b c"). So in your getopt case, when quoted as "$argv" the arguments are passed to getopt(1) as a single string, not as a list of individual elements, and getopt(1) fails as it wants a list of items, not a single string.
A strace on bash should show what "$@" does; one hypothesis would be that it splits the elements out to a list instead of smushing them together as a single item.
| Is $argv in fish shell different from $@ in bash? |
1,470,216,637,000 |
Situation: Need to login to multiple remote servers with some of them having fish shell
Requirement: Default shell is bash. If I login to a server and fish is present, switch to fish shell, otherwise stay on bash.
Tried .bashrc:
# .bashrc
# Source global definitions
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
# Source global definitions
if [ -f /etc/bash.bashrc ]; then
. /etc/bash.bashrc
fi
# Update Path
export PATH=/sbin:/usr/sbin:/usr/local/sbin:$PATH:$HOME/.bin
# Open fish shell if present, otherwise stick to bash
if hash fish 2>/dev/null; then
# echo "Fish detected, shifting shell"
fish "$@"; exit
fi
However, scp doesn't seem to be working. When I try to scp a file, verbose output shows it to be stuck here.
debug1: Authentication succeeded (publickey).
debug1: channel 0: new [client-session]
debug1: Requesting [email protected]
debug1: Entering interactive session.
debug1: pledge: network
debug1: client_input_global_request: rtype [email protected] want_reply 0
debug1: Sending environment.
debug1: Sending env LANG = en_US.UTF-8
debug1: Sending env LC_ADDRESS = en_US.UTF-8
debug1: Sending env LC_IDENTIFICATION = en_US.UTF-8
debug1: Sending env LC_MEASUREMENT = en_US.UTF-8
debug1: Sending env LC_MONETARY = en_US.UTF-8
debug1: Sending env LC_NAME = en_US.UTF-8
debug1: Sending env LC_NUMERIC = en_US.UTF-8
debug1: Sending env LC_PAPER = en_US.UTF-8
debug1: Sending env LC_TELEPHONE = en_US.UTF-8
debug1: Sending env LC_TIME = en_US.UTF-8
debug1: Sending command: scp -v -f test_file
Initially I thought the echo command was causing it to not work, but it doesn't work without it as well.
|
To exit the bashrc file when the shell session that is sourcing it is not interactive, you may do the following at the top (or in a convenient location) of the file:
case "$-" in
*i*) ;;
*) return ;;
esac
The value in $- is a string of letters denoting the currently set shell options. If the i character is present in the string, then the shell is interactive.
This may be needed since, as terdon pointed out in comments, Bash treats shell sessions that are started by sshd, the SSH daemon, as a special case.
Details: Why does bashrc check whether the current shell is interactive?
Further down in the file, you may check whether the fish shell is available and start that:
if command -v fish 2>/dev/null; then
exec fish
fi
Be aware that fish may be the game of "Go Fish" on some systems :-)
About the use of command -v: Why not use "which"? What to use then?
| Issues with scp if I use bashrc to open fish if present |
1,470,216,637,000 |
I have downloaded fish shell on my centos, but when I switch command to /bin/fish
or even try to run xterm -e /bin/fish
I am getting following error:
Standard input: echo $_ " "; __fish_pwd
^
in command substitution
called on standard input,
Standard input: __fish_pwd
^
in command substitution
called on standard input,
in command substitution
called on standard input,
Standard input: echo $_ " "; __fish_pwd
^
in command substitution
called on standard input,
I also tried xterm -e 'tcsh -i -c fish' this too gave same error
|
The issue here is that fish cannot find its function directory.
The rpm you downloaded has been built with a certain $fish_function_path, and those values aren't valid.
What you'd need to do is adjust those to where you actually placed the files - something like set fish_function_path ~/.config/fish/functions /etc/fish/functions /usr/san/documents/share/fish/functions.
(Also I think the error message has improved in newer fish versions)
| launching fish shell to new terminal of tcsh on centos |
1,470,216,637,000 |
The fish documentation gives the following way to run a for loop.
for i in 1 2 3 4 5;
echo $i
end
Let us say I want to run a command 1000 times, How can I do it?
|
Same documentation, https://fishshell.com/docs/current/language.html#loops-and-blocks :
for i in (seq 1 5)
echo $i
end
replace seq 1 5 with the numbers you want to get, e.g., seq 14 1000 to get the numbers from 14 to 1000; if you want to start at 1, it's OK to omit the starting point, i.e., write seq 1000.
This, by the way, is like very classical UNIX shells; doesn't feel very modern. (In bash and zsh you can do for i in {1..1000}, which I consider easier and clearer to read, not to mention that it saves actually running an external program seq and buffering its output.)
Another way, which doesn't rely on coreutils (which is kind of a sad thing to rely on if you're not a GNU program nor a POSIX shell), would be using the while loop and purely fish builtin functions:
set counter 0
# -lt: less than
while test $counter -lt 1000;
set counter (math $counter + 1)
echo $counter
end
| How to run a command n times in the fish shell? |
1,470,216,637,000 |
How can I use sed to replace new line character with any other character?
Input:
I cannot conceive that anybody will
require multiplications at the rate of
40,000 or even 4,000 per hour ...
-- F. H. Wales (1936)
Desired output:
I cannot conceive that anybody will require multiplications at the rate of 40,000 or even 4,000 per hour ... -- F. H. Wales (1936)
I've tried:
> pbpaste | sed 's/\n/ /g'
but it outputs the same thing as input. I know it's a newline char because I've checked it with cat -ev and it prints $ as expected.
What else would be a good command to do this?
This shows where there is extra space between new line. I want to remove that as well. So it's like a sentence with spaces.
> pbpaste | cat -ev
I cannot conceive that anybody will $
require multiplications at the rate of $
40,000 or even 4,000 per hour ... $
$
-- F. H. Wales (1936) ‚èé
|
tr is probably a better tool for this job. Try the following
pbpaste | tr '\n' ' '
With your input, I get the following output.
I cannot conceive that anybody will require multiplications at the rate of 40,000 or even 4,000 per hour ... -- F. H. Wales (1936)
| sed replace newline character with space |
1,470,216,637,000 |
I'm trying to shift to fish from zsh. As I've seen, load time of fish increases if I use alias. So I'd like to convert all of my alias into functions, but the thing is creating a function script for every alias is a bit hectic. So how do I add those alias in a single function script?
|
Based this Stack Overflow example by ridiculous_fish, I would suggest creating a file under ~/.config/fish/ with the functions defined in them, then add a line to source that file in your ~/.config/fish/config.fish file.
Example contents of ~/.config/fish/all-my-functions.fish:
function example-function1
ls -l $argv
end
function example-function2
ls -a $argv
end
# continues as needed ...
and the line for ~/.config/fish/config.fish:
source ~/.config/fish/all-my-functions.fish
Alternatively, you could define all of the functions directly into your config.fish file.
| How do I add multiple fish functions in a single script? |
1,470,216,637,000 |
I have tool that is able to create a completion file for bash, zsh and fish. I normally use zsh, but i cannot get this completion file to work on zsh. So as a test i installed fish and created the completion file for fish. Also that one i cannot get to work. All other completions are working fine in zsh and in fish, so i suspect that the tool creates a broken completion file.
Is there a way to check the syntax of a completion file for errors?
|
My answer addresses zsh (with the “new” completion system, i.e. after calling compinit) and bash. For fish, see NotTheDr01ds's answer.
If there is a syntax error in the completion file, you'll see an error message when the completion code is loaded. In bash, this happens when /etc/bash_completion is loaded. In zsh, this happens the first time the completion function is invoked. But syntax errors are rare. Most errors are not syntax errors, and there's no way to check whether a completion function works other than invoking it.
If an actual error happens while generating the completions, you'll see an error message on the terminal. But if the code doesn't trigger an error, but doesn't generate the desired completions, then there's no error to display.
The first thing to check is whether the completion function you want is actually invoked. For zsh, check
echo $_comps[foo]
where foo is the command whose options/arguments are to be completed. For bash, check
complete -p foo
If your custom completion function isn't loaded, see Dynamic zsh autocomplete for custom commands or Custom bash tab completion.
If you want to debug the completion code, in zsh, press ^X? (Ctrl+X ?) instead of Tab to run _complete_debug. This places a trace of the completion code into a file which you can view by pressing Up Enter.
| Is there a way to validate a completion file? |
1,470,216,637,000 |
I recently started using the Fish shell.
echo $EDITOR returns vim
But yet, when using programs that need to launch an editor and look for it in the EDITOR environment variable they don't seem to find anything.
As an example when using pass edit (from https://www.passwordstore.org/) it returns
vi: command not found (it uses vi as a fallback when nothing is set in the EDITOR env variable)
What did I miss?
|
Note that a few programs look for the $VISUAL environment variable before the $EDITOR environment variable, so if you have both set, $VISUAL will take precedence.
Also note that shell variables are just that, variables in the shell language. You'd need to call commands with EDITOR=preferred-editor in their environment for them to pick it up.
Shells can map some of their variables to environment variables that are then passed as var=value in the environment of all the commands they execute. In rc-like shells, that's done for all shell variables, in Bourne-like shells, that's done with export var. In csh, you use setenv var value to set an environment variable. In fish, you use the -x option of set:
> set var value
> echo $var
value
> printenv var
>
A $var shell variable was set, but not exported (as var=value) to the environment passed to printenv.
> set -x var value2
> echo $var
value2
> printenv var
value2
This time, printenv did get a var=value2 in the environment it received.
printenv is not a standard command but is commonly available. env is a standard command, so if your system doesn't have printenv, you could try:
env | grep -E '^(VISUAL|EDITOR)='
Though it could be fooled if you had variables with values such as var=<newline>VISUAL= or values larger than LINE_MAX.
Other options could be:
perl -le 'print $ENV{VISUAL}'
python -c 'import os; print(os.getenv("VISUAL"))'
Also note that though it is highly unlikely to be the case here, it is possible to execute a command with more than one var=value for a given var in their environment.
For instance, you could do
execve("/path/to/cmd", ["cmd", "some arg"], ["VISUAL=vi", "VISUAL=emacs"])
What value cmd will consider the VISUAL environment variable as having will depend on how they scan that env var list they received upon exceve(). You'll find that some commands / libraries (like libc's getenv()) will pick the first while some will pick the last. Some shells will map one of them to their corresponding env var but may leave the other one around and passed along in further executions.
So you could be doing set -x VISUAL vim, and printenv seeing emacs because fish was executed with both VISUAL=vi and VISUAL=emacs and only modified the first VISUAL whilst printenv gives you the second.
For this kind of thing to happen though, you'd need something or someone actively trying to trick you, and after double checking, it seems fish is one of those shells that do remove the duplicates from the environment if any.
| Fish EDITOR environment variable does not seem to work |
1,470,216,637,000 |
I'd like to take the csearch output and color it. It looks like so:
/home/bp/whatever.txt:1:foo
And this works:
csearch -n -- $term \
| env GREP_COLORS='mt=02;35' grep --color=always -P '^[^:]+:[^:]+:' \
| grep -P --color=always -- $term \
| less -RFX
However, it waits for the full output of csearch to be computed before anything is shown.
Now, if I do this:
csearch -n -- $term \
| env GREP_COLORS='mt=02;35' grep --color=always -P '^[^:]+:[^:]+:' \
| pv
| grep -P --color=always -- $term \
| less -RFX
...I can see the data flowing, but if I do this:
csearch -n -- $term \
| env GREP_COLORS='mt=02;35' grep --color=always -P '^[^:]+:[^:]+:' \
| grep -P --color=always -- $term \
| pv
| less -RFX
...no data is flowing. The second grep seems to be waiting for an EOF.
Adding --line-buffered to both grep's seems to be doing me no good.
Why is this command pipe waiting for EOF?
|
I was using fish, which means I wasn't actually using grep, but:
function grep
command grep --color=auto $argv
end
and fish code blocks do not stream their output.
This wasn't a problem in the first grep since it was already wrapped by env, so it ignored this function.
Changing grep to /bin/grep fixed it.
| Output pipe waits for EOF in fish [closed] |
1,470,216,637,000 |
A quick google search says I could enable auto logout (for text consoles) by setting a TMOUT parameter. However, I discovered later that this would only work with the bash shell.
Is there a way I could set a timer for auto logout if my default shell was fish?
What is the purpose? Security, of course. I want it to lock when it's idle for 1 minute.
|
While Fish itself doesn't include support for TMOUT directly, there are a few alternatives that might work for you. Given the fact that my two approaches are so radically different, I'm going to include them in two separate answers.
First (and not my preferred approach, but it's closest to the Bash functionality), depending on your Fish version:
Short answer:
Create a new file ~/.config/fish/conf.d/fish_tmout.fish:
function start_logout_timer --on-event fish_prompt
# Allows $last_pid to work in a function
status job-control full
if set --query __fish_tmout_pid
# Stop previous timer
kill -- -$__fish_tmout_pid
end
# Start new timer
FISH_PID=%self sh -c "sleep 60; kill -HUP $FISH_PID" &
# Allows logout without warning of background jobs
disown
set -gx __fish_tmout_pid $last_pid
end
function stop_logout_timer --on-event fish_preexec
if set --query __fish_tmout_pid
kill -- -$__fish_tmout_pid
end
set --erase __fish_tmout_pid
end
Restart your shell and you should find that you are automatically logged out after 1 minute of no activity in the shell.
Compatibility: At least Fish 3.2.2 and later. Known to not work on 3.0.2 and earlier.
Minor caveat: You will always have an extra "defunct sh" hanging out when you do a ps.
Note: This does handle multiple shell instances running, since each shell is tracking its own PID and timer in a global (not universal) variable.
Explanation:
You can attempt to replicate that Bash functionality through other Fish features. But since (from your comment on Stack Overflow), you want this in order to secure the session from other people around you in case you forget to log out, you should be aware of the limitations of both this and the TMOUT option available in other shells. Namely, if you walk away while using any "full-screen" app that has control of the terminal (e.g. less, vim, or plenty of others), then it's not going to work. TMOUT is only handled when you leave Bash idle at the prompt.
Likewise, this approach has the same limitation. With that in mind ...
The Bash manual has this to say about TMOUT:
In an interactive shell, the value is interpreted as the number of seconds to wait for a line of input after issuing the primary prompt. Bash terminates after waiting for that number of seconds if a complete line of input does not arrive.
In Fish parlance, that would be either:
The time period between the display of two consecutive prompts
The time period between the display of a prompt and the user entering an interactive command
Which can be handled by Fish function hooks for:
fish_prompt
fish_preexec
So the script above:
Starts an auto-logout timer (via sleep) when the prompt is displayed (fish_prompt)
Stops that timer (by killing the subprocess owning the timer and logout) when either the next prompt is displayed (fish_prompt) or a command is entered (fish_preexec).
Logs out of the shell (via SIGHUP) when the timer expires without being killed
| How to enable auto logout in fish shell? |
1,621,502,663,000 |
I'm already scratching my head for a while because of this:
> cat file
line1
line2
> set tst (cat file)
> echo "$tst"
line1 line2
> set tst "(cat file)"
> echo "$tst"
(cat file)
In bash I can get it done like so:
$ cat file
line1
line2
$ tst=$(cat file)
$ echo "$tst"
line1
line2
|
By default, fish splits command substitutions ((command)) on newlines. To override that behavior, you can use the special string subcommands like string split (which allows you to define what to split on), string split0 (which splits on NUL bytes) and string collect (which doesn't split at all[0]).
So the answer is:
set tst (cat file | string collect)
echo $tst
[0]: Note that NUL bytes can't be passed to commands because unix passes the arguments as NUL-terminated strings, so there is no way for the command to know that the argument goes on, so string collect effectively just captures the command output up to the first NUL, giving you at most one entry, while string split0 might result in multiple arguments.
| How to preserve formatting in fish shell command substitution output stored in the var? |
1,621,502,663,000 |
I have a function that is setup to send status updates to anybar.
function e --description 'Run command' \
--argument-names command
anybar yellow; eval $command; anybar green;
end
I am trying to find a way wrap all of my commands that I give through cli to fish in this function.
Does anyone know if this is possible?
|
Instead of this method, try adding the following to your config.fish:
function my_preexec --on-event fish_preexec
anybar yellow
end
function my_postexec --on-event fish_postexec
anybar green
end
This will run these functions before and after every command, without requiring the potentially-explosive eval.
| Fish Wrap all commands in a function |
1,621,502,663,000 |
I noticed the error this morning, but I don't think I have changed anything last night, so I am very confused right now. Perhaps I updated some utilities on my system and it somehow broke the back compatibility. Basically I got a math: Error: Missing operator error when using tab completion.
Say I type fish, and hit Tab to get the suggestions like fish_config and fish_add_path (here is an asciinema screencast in case you want to see it in action: https://asciinema.org/a/L3xr32eVMGHuCY0Gjr19gFzCu)
[I] ~ $ fishmath: Error: Missing operator
'Wed Dec 31 18:00:00 CST 1969 - 1655913830'
^
[I] ~ $ fish_config
fish (command)
fish_add_path
fish_breakpoint_prompt
fish_clipboard_copy
…and 29 more rows
The tab completion does work, but the error looks very annoying. Looks like I am trying to evaluate a data string or something. How do I diagnose the bug?
I am on macOS Monterey. Here is my ~/.config/fish/config.fish.
set -px PATH /opt/local/bin /opt/local/sbin
set -px PATH $HOME/.local/bin
set -px PATH $HOME/bin
set -px PATH /Applications/MacPorts/Alacritty.app/Contents/MacOS
set -px PATH $HOME/Foreign/drawterm
set -px PATH $HOME/google-cloud-sdk/bin
set -x XDG_CONFIG_HOME $HOME/.config
set -x PIPENV_VENV_IN_PROJECT 1
set -x PLAN9 /usr/local/plan9
set -px PATH $PLAN9/bin
if test -e $HOME/.config/fish/sensitive.fish
source $HOME/.config/fish/sensitive.fish
end
if status is-interactive
# Commands to run in interactive sessions can go here
alias vi='/opt/local/bin/nvim'
set -gx EDITOR /opt/local/bin/nvim
source /opt/local/share/fzf/shell/key-bindings.fish
end
set -g fish_key_bindings fish_hybrid_key_bindings
alias matlab='/Applications/MATLAB_R2021b.app/bin/matlab -nodisplay'
zoxide init fish | source
direnv hook fish | source
# The next line updates PATH for the Google Cloud SDK.
if [ -f '/Users/qys/google-cloud-sdk/path.fish.inc' ]; . '/Users/qys/google-cloud-sdk/path.fish.inc'; end
|
The error goes away after I remove the line set -px PATH $PLAN9/bin. I guess it was because I accidentally shadowed some system utilities with its counterpart in Plan 9 from User Space.
Another workaround is to use set -ax PATH $PLAN9/bin instead. By using -a, the directory $PLAN9/bin is appended to $PATH (as opposed to prepended when using -p), so that the commands already present in $PATH takes precedence over the Plan 9 ones.
| Fish shell reports "math: Error: Missing operator" on tab completion |
1,621,502,663,000 |
Oh-my-zsh has the take command which creates a directory and enters into it in one step. Is there an equivalent command for the fish shell?
I do know that I can do it with mkdir newDir && cd newDir, but I like the shorter, more convenient version that Oh-my-zsh provides.
|
Not built-in, but very easy to reproduce:
function take
mkdir -p "$argv[1]"; and cd "$argv[1]"
end
funcsave take
This will create a lazy-load function in $HOME/.config/fish/functions/take.fish. By "lazy-load", we mean that the function isn't loaded when Fish starts, but only the first time you run the take command. So it's always available, but only takes up memory when you run it.
| Oh-my-zsh "take" command - Is there an equivalent in Fish? |
1,621,502,663,000 |
I am using fish and am working on a project with a script that's frequently invoked for build tasks called x.py. I'd like to create an alias that maps x to ./x.py. However, I only want this to apply inside that specific directory.
The fish documentation gives a fairly detailed explanation on how to make various kinds of aliases/functions/etc, but I can't find anything on how to make them directory specific.
Any help would be much appreciated
|
Three possibilities that I can think of (other than the ones that Damir suggested). First, if at all possible, I'd just test whether or not you are in the directory in a "lazy-load" function. This is similar to what Damir recommended, but it avoids the overhead of being in your startup config or in an executable script.
Lazy-load function-based solution
Create ~/.config/fish/functions/x.fish:
function x
if [ (pwd) = "/path/to/project` ]
./x.py
else
command x
end
end
This function will only load when called for the first time via x. This avoids the overhead of adding it to your startup config. It is also still a function, so it executes in the current fish shell, rather than starting a new shell like an executable script would.
It also falls back to any other x command that might be installed on the system in case you aren't in that directory. If you don't need this, just delete the else block.
Function which is created when you enter the project directory
If you really need to have the function only exist when you are in that directory, there are two more alternatives. First, fish functions can watch for a variable to change, and only run when it does. That variable can be $PWD to watch for a directory change.
Add the following in ~/.config/fish/conf.d/create_x.fish:
function create_x --on-variable PWD
if [ "$PWD" = "/path/to/project" ]
function x
./x.py
end
else
functions --erase x
end
end
This does require the create_x.fish function to be loaded at startup, but it will only run when you change directories. It's definitely less efficient than the first option.
Prompt-based function
Finally, you can modify your prompt function to check the current directory. This seems wasteful, but:
funced fish_prompt
Add the following to the bottom:
functions --erase x
if [ (pwd) = "/path/to/project" ]
function x
./x.py
end
end
funcsave fish_prompt
This will check to see if you are in the project directory on each prompt, and will only create the function if you are.
The funcsave places a copy of the "normal" fish_prompt in your ~/.config/fish/functions directory. Delete it to return to the normal prompt functionality.
Definitely, go with the first option if you can :-)
| fish shell alias only in specific directory |
1,621,502,663,000 |
I'm pretty certain this is some foible of my SSH client (RoyalTS for Windows) but, having just installed and changed to fish shell, my prompt is preceded by two dark-grey ⎠characters.
It doesn't seem to do it in PuTTY, just in this particular client, which uses a Rebex plugin.
The fish FAQ talks about random characters and mentions a fish_title function, which it tells you how to empty, but this does not seem to have made a difference.
I'm sure they are just some sort of mis-encoded control characters, but I'm just trying to work out what these two characters are, what they are for and how I might get rid of them.
Edit
As requested, the output of fish_prompt hasn't changed since install, and is:
function fish_prompt --description 'Write out the prompt'
# Just calculate this once, to save a few cycles when displaying the prompt
if not set -q __fish_prompt_hostname
set -g __fish_prompt_hostname (hostname|cut -d . -f 1)
end
set -l color_cwd
set -l suffix
switch $USER
case root toor
if set -q fish_color_cwd_root
set color_cwd $fish_color_cwd_root
else
set color_cwd $fish_color_cwd
end
set suffix '#'
case '*'
set color_cwd $fish_color_cwd
set suffix '>'
end
echo -n -s "$USER" @ "$__fish_prompt_hostname" ' ' (set_color $color_cwd) (prompt_pwd) (set_color normal) "$suffix "
end
...and fish_prompt | xxd:
0000000: 726f 6f74 4063 616e 6463 2d77 6230 3170 root@candc-wb01p
0000010: 2d6c 201b 5b33 316d 2f1b 5b33 306d 1b28 -l .[31m/.[30m.(
0000020: 421b 5b6d 2320 B.[m#
...and functions -an:
# functions -an
., N_, _, __fish_append, __fish_bind_test1, __fish_bind_test2,
__fish_command_not_found_setup, __fish_commandline_test,
__fish_complete_abook_formats, __fish_complete_ant_targets,
__fish_complete_atool, __fish_complete_atool_archive_contents,
__fish_complete_aura, __fish_complete_bittorrent,
__fish_complete_cabal, __fish_complete_cd, __fish_complete_command,
__fish_complete_convert_options, __fish_complete_diff,
__fish_complete_directories, __fish_complete_file_url,
__fish_complete_ftp, __fish_complete_grep, __fish_complete_groups,
__fish_complete_list, __fish_complete_lpr, __fish_complete_lpr_option,
__fish_complete_ls, __fish_complete_lsusb, __fish_complete_man,
__fish_complete_mime, __fish_complete_pacman, __fish_complete_path,
__fish_complete_pgrep, __fish_complete_pids, __fish_complete_ppp_peer,
__fish_complete_proc, __fish_complete_python,
__fish_complete_service_actions, __fish_complete_setxkbmap,
__fish_complete_ssh, __fish_complete_subcommand,
__fish_complete_subcommand_root, __fish_complete_suffix,
__fish_complete_svn, __fish_complete_svn_diff, __fish_complete_tar,
__fish_complete_tex, __fish_complete_unrar, __fish_complete_users,
__fish_complete_vi, __fish_complete_wvdial_peers, __fish_complete_xsum,
__fish_config_interactive, __fish_contains_opt, __fish_crux_packages,
__fish_cursor_konsole, __fish_cursor_xterm,
__fish_default_command_not_found_handler, __fish_describe_command,
__fish_filter_ant_targets, __fish_filter_mime, __fish_git_prompt,
__fish_gnu_complete, __fish_hg_prompt, __fish_is_first_token,
__fish_is_token_n, __fish_list_current_token,
__fish_make_completion_signals, __fish_man_page, __fish_move_last,
__fish_no_arguments, __fish_not_contain_opt,
__fish_number_of_cmd_args_wo_opts, __fish_paginate, __fish_ports_dirs,
__fish_print_abook_emails, __fish_print_addresses,
__fish_print_arch_daemons, __fish_print_cmd_args,
__fish_print_cmd_args_without_options, __fish_print_commands,
__fish_print_debian_services, __fish_print_encodings,
__fish_print_filesystems, __fish_print_function_prototypes,
__fish_print_help, __fish_print_hostnames, __fish_print_interfaces,
__fish_print_lpr_options, __fish_print_lpr_printers,
__fish_print_lsblk_columns, __fish_print_make_targets,
__fish_print_mounted, __fish_print_packages,
__fish_print_service_names, __fish_print_svn_rev, __fish_print_users,
__fish_print_xdg_mimeapps, __fish_print_xdg_mimetypes,
__fish_print_xrandr_modes, __fish_print_xrandr_outputs,
__fish_print_xwindows, __fish_prt_no_subcommand, __fish_prt_packages,
__fish_prt_ports, __fish_prt_use_package, __fish_prt_use_port,
__fish_pwd, __fish_reconstruct_path, __fish_reload_key_bindings,
__fish_repaint, __fish_repaint_root, __fish_restore_status,
__fish_seen_subcommand_from, __fish_systemctl_automounts,
__fish_systemctl_devices, __fish_systemctl_mounts,
__fish_systemctl_scopes, __fish_systemctl_service_paths,
__fish_systemctl_services, __fish_systemctl_slices,
__fish_systemctl_snapshots, __fish_systemctl_sockets,
__fish_systemctl_swaps, __fish_systemctl_targets,
__fish_systemctl_timers, __fish_test_arg, __fish_urlencode,
__fish_use_subcommand, __fish_winch_handler, __terlar_git_prompt, abbr,
alias, cd, contains_seq, cp, delete-or-exit, dirh, dirs,
down-or-search, eval, export, fish_config, fish_default_key_bindings,
fish_indent, fish_mode_prompt, fish_prompt, fish_sigtrap_handler,
fish_update_completions, fish_vi_cursor, fish_vi_key_bindings,
fish_vi_mode, funced, funcsave, grep, help, history, hostname, isatty,
la, ll, ls, man, math, mcd, mimedb, mv, nextd, nextd-or-forward-word,
open, popd, prevd, prevd-or-backward-word, prompt_pwd, psub, pushd, rm,
seq, setenv, sgrep, trap, type, umask, up-or-search, vared,
|
I'm sure they are just some sort of mis-encoded control characters, but I'm just trying to work out what these two characters are,
⎠is what happens when one displays the transmitted octets \xc2 \x8e decoded with Windows code page 1252. Your terminal emulator is using a single-byte character set.
Decoded as UTF-8, rather, that is the SS2 control character.
So you have: something on the host end that thinks that it needs to send ISO 2022 control sequences to switch 7-bit character sets, even though (quite ironically) it's encoding those control sequences in UTF-8; and a terminal emulator that isn't speaking UTF-8.
There's more ISO 2022 in the prompt string that you hex-dumped. \x1b \x28 \x42 is where your shell (apparently in its set_color normal command) sent the ISO 2022-JP sequence to switch to ASCII.
The simplest cure is this: Make your terminal emulator speak UTF-8. Stop your host programs thinking that they need to do any sort of ISO 2022 character set switching at all and tell them to just speak UTF-8 too.
You might want to check your terminal type, too. Your terminal type (sent originally from your terminal emulation program to your host) must match the actual behaviour of your terminal emulation program. Making "But it's xterm, right?" decisions, or just picking arbitrary terminal types, rarely works well.
The right terminal type for PuTTY is in fact something like putty or putty-256color or putty-sco for example.
| Fish shell shows dark-grey "âŽ" characters in prompt |
1,621,502,663,000 |
I'm running Fish version 3.7.0, and I want to write a function to remove elements from lists, based on their index.
For instance, I want to remove the element from PATH environment variable at index 2:
set -l variable_name PATH
set -l index 2
set -e $variable_name[$index]
However, the follow statement does not work, it returns:
set: --erase: option requires an argument
I see it requires some lazy evaluation to get the variable name (e.g. PATH), but I didn't figure how to do that.
|
The issue is that fish takes $var[$foo] as "the footh element of $var", where you want "expand $var, expand $foo, and attach both together".
You can use a variety of ways to express what you want, the cleanest is probably:
set -e $variable_name[1][$index]
This will expand the first element of $variable_name ("PATH"), the other [] will not be syntactically special, so it will end up running
set -e PATH[2]
like you want.
Alternatives include quoting (set -e "$variable_name"[$index]), brace expansions (set -e {$variable_name}[$index]) - you really just need to separate the $var from the [$foo] part. Even setting index to [2] and using set -e $variable_name$index works.
| Fish needs a lazy evulation to remove an element from a list |
1,621,502,663,000 |
I was wondering if there is an easy way to configure ZSH (I am using oh-my-zsh) and/or FISH (just started fiddling with this) to not keep the cursor/promt at the bottom of the terminal as soon an the buffer exceeds the number of displayable lines but rather at the middle of the screen.
The reason for this is that I keep staring at the bottom of my screen when navigating in the console but working mostly in the middle of the terminal when for example doing work in VIM. I would like to try such a behavior to see if that.
|
A quick trial shows this seems to work in ZSH:
PS1=$'\n\n\n\n\n\n\n\n\e[8A'"$PS1"
This has the prompt print 8 newlines, then moves the cursor back up 8 lines with the \e[8A escape code, before printing the actual prompt.
You can add more newlines and increase the scroll-up to match, depending how far off the bottom you want to be.
| Keep cursor/prompt vertically centered in ZSH/FISH |
1,621,502,663,000 |
To improve compile times, the Arch wiki states,
Users with multi-core/multi-processor systems can specify the number
of jobs to run simultaneously. This can be accomplished with the use
of nproc to determine the number of available processors, e.g.
MAKEFLAGS="-j$(nproc)".
If I set this in Fish shell via set -Ux MAKEFLAGS "-J$(nproc)", then I receive the error:
fish: $(...) is not supported. In fish, please use '(nproc)'.
set -Ux MAKEFLAGS "-J$(nproc)"
^
I can set this variable in two ways without receiving an error:
set -Ux MAKEFLAGS "-J(nproc)"
set -Ux MAKEFLAGS '-J$(nproc)'
Which of these is the correct method? Or are they both okay?
Thanks
|
Neither. In fish, command substitution cannot be quoted.
set arg "-J(nproc)"
set -S arg
$arg: set in global scope, unexported, with 1 elements
$arg[1]: |-J(nproc)|
Use
set -Ux MAKEFLAGS "-J"(nproc)
| What's the correct format for MAKEFLAGS when using Fish shell? |
1,621,502,663,000 |
I am using iTerm2 on my mac pro, and using fish as my shell. Every time I have a process running and I break it by pressing ctrl+c, the arrow keys stops working after and starts emitting ^[[A etc.
Attached a screenshot to my iTerm2 preferences > Profiles [Default] > Terminal
|
The program has switched to application mode for the cursor-keys (and does not cleanup when interrupted). You can manually switch back using this command:
tput rmkx
Some terminal emulators have a setting in a dialog which lets you do the same thing.
| MacOS/iTerm2/fish arrow keys stops working after terminating a process with ctrl+c |
1,621,502,663,000 |
I changed the default shell with
chsh -s `which fish`
but my terminal still launches with bash. If I run chsh again, it says chsh: Shell not changed. I'm using Manjaro x86_64 20.2.1 with XFCE (4.16). This is a mainly clean install (like 4 days old), only really having neofetch, and fish.
|
Fixed the problem by rebooting. I feel silly now
| xfce terminal ignores set default shell |
1,621,502,663,000 |
I made fish function in ~/.config/fish/functions/confgit.fish:
function confgit
/home/john/Projects/confgit $argv
end
But when I run this function it just says:
fish: The file “/home/john/Projects/./confgit” is not executable by this user
/home/john/Projects/./confgit $argv
^
in function 'confgit'
The config file is normal python script. If I run it by ./confgit it runs fine.
There are the permissions of the script:
-rwxr-xr-x 1 john john 5.8K 29. nov 02.04 confgit*
How can I fix this so I can use this function ?
Thank you for help
|
I worked to reproduce your problem, and the closest thing I could emulate was this:
# file: ~/bin/janstest
echo $argv
# file: ~/bin/janstest2
function janstest
~/bin/janstest $argv
end
janstest It works!
and file permissions as:
stew@stewbian ~> ls -l ~/bin/jans*
-rwxr-xr-x /home/stew/bin/janstest*
-rwxr-xr-x /home/stew/bin/janstest2*
When I run it I get a similar error:
stew@stewbian ~> ~/bin/janstest2
Failed to execute process '/home/stew/bin/janstest2'. Reason:
exec: Exec format error
The file '/home/stew/bin/janstest2' is marked as an executable but could not be run by the operating system.
stew@stewbian ~ [125]>
The solution was to prepend #!/usr/bin/fish to the the script.
stew@stewbian ~> cat ~/bin/janstest2
#!/usr/bin/fish
function janstest
~/bin/janstest $argv
end
janstest It works
stew@stewbian ~> ~/bin/janstest2
It works
| Fish: The file is not executable by this user |
1,621,502,663,000 |
I am using the fish shell and try to log stdout and stderr into two separate files and printing them in the terminal at the same time (e.g., by piping each stream to tee).
In bash I would do (see https://stackoverflow.com/a/692407/5082444):
command > >(tee -a stdout.log) 2> >(tee -a stderr.log >&2)
How can I achieve the same in the fish shell?
|
You can do something similar with
begin; command | tee -a stdout.log ; end ^| tee -a stderr.log >&2
with the proviso that if the first tee writes anything to stderr, it will also get logged, which is not the case with the bash version.
| Print and log stdout and stderr in fish shell |
1,621,502,663,000 |
Is this even possible?
I'd like to run a command but capture its stdout and stderr as separate variables. Currently I'm using set -l var (cmd), which leaves stderr untouched. I can do set -l var (cmd ^&1) which will merge stdout and stderr into var, but then I can't easily separate them again.
Is there any way to get var and var_err to hold stdout and stderr from cmd?
|
begin; cmd ^|read -z err; end |read -z out
From fish-shell/fish-shell #2463,
An issue in your fish example is that it redirects [stdout] of both [cmd] and [read], so if the latter prints anything, it'll be carried through the pipe.
But I don't think read should ever print anything (especially to stdout) in the normal case, so this should be fine.
Edit: If the exact semantics of set var (cmd) are needed, that can be achieved using set var (printf '%s' $out) and set var_err (printf '%s' $err)
| Capture stdout and stderr as separate variables in fish shell |
1,621,502,663,000 |
The fish shell uses many escape sequences as you type, especially if you ever make a mistake or use completion.
'script' just captures them literally, making quite a mess. More of a mess than col -b can repair.
Is there some other way to record command lines and their results (other than just using an emacs shell buffer, which I might resort to)?
Is there a way to configure fish to, ahem, scale back it's fancy display?
|
You'll lose many of the nice features of fish - colourisation, autosuggestions, etc., but you can start script with the environment variable TERM set to dumb. This will result in a much cleaner output. script really is a dumb terminal - the manpage suggests that it is supposed to emulate an old-style hardcopy terminal!
env TERM=dumb script
| fish + script -> chaos, what options? |
1,621,502,663,000 |
First of all, I'm on OSX10. My default shell is BASH, which I have set up (through .profile and .bashrc) to automatically run the FISH shell when I open my terminal emulator. This allows me to set up variables etc. in BASH before I load up FISH.
Sometimes, however, I want to run scripts which are written for BASH, from my FISH shell. This is necessary because FISH isn't syntactically compatible with BASH. When typing 'bash' in my FISH, the BASH I open automatically opens another FISH on top of itself, because of my .profile/.bashrc. That makes it all fishy (pun intended), because I then have to exit the top FISH to get into the BASH on top of the second FISH.
My question is: I know BASH can be loaded up as a login shell (executing .profile), and a non-login shell (executing .bashrc). Would it be possible to add a third 'context', which I can set up to load when BASH is run from inside FISH? That would solve the double-FISH problem because I'd be able not to load either .bashrc or .profile.
I hope you understand my question -- thanks in advance for answers!
|
You could set a variable in the script which starts fish to note that you're "in fish":
export IN_FISH=yes
Then, before that, you check whether it's already set:
if [ "${IN_FISH}" != "yes" ]; then
export IN_FISH=yes
fish # replace with the command you use to start fish
fi
Thus, in your first bash, IN_FISH isn't set, so it gets set and fish is started. When you start bash from FISH, IN_FISH is already set, so bash doesn't start fish again...
| Custom bash 'context' when running from FISH |
1,621,502,663,000 |
In bash, you can pipe the same output to two commands using {}, i.e. in the following:
cmd0 | { cmd1 ; cmd2 ;} | cmd3
cmd1 and cmd2 get the output of cmd0 in their stdin, and cmd3 gets the output of cmd2 appended to output of cmd2 in its stdin.
What's the name of this {} feature and is there an equivalent in fish?
|
The feature is called command grouping.
In the fish shell, it appears to be provided by using begin and end in place of bash's { and } braces - a feature I only discovered from a bug report:
begin-end command grouping isn't discoverable/documented prominently enough #6415
Note that regardless of shell, the first command that is able to do so will consume standard input ex.
(bash):
$ echo foo | { sed 's/oo/aa/'; sed 's/oo/um/'; }
faa
(fish):
> echo foo | begin sed 's/oo/aa/'; sed 's/oo/um/'; end
faa
but
> echo foo | begin echo cmd1 ; sed 's/oo/um/'; end
cmd1
fum
| fish equivalent for sequence of commands -- { cmd1 ; cmd2; } |
1,621,502,663,000 |
I've added a command to start fish terminal from bashrc and so far it was working ok.
I've just added this line at the end of bashrc
fish
But after I quit fish to default shell current input isn't displayed anymore, although pressing enter will interpret whatever was typed.
Is there any other way to start fish automatically without affecting standard input stream?
|
When you exit the fish shell session, the bash shell that was starting up but that was "put on hold" while fish was running, continues to run. For whatever reason, it leaves the terminal in a confused state (try reset or stty sane to fix that).
If you always want to run the fish shell instead of bash, then it would be easier to just change your login shell to fish. You do this with the chsh command on most Unices.
If that's not possible, then rather than just running fish from you ~/.bashrc file, use exec fish from somewhere in the beginning the file. This would replace any interactive bash shell session with a fish shell session, and when you exit the fish session, you would not be left in a bash session.
| Starting Fish terminal from bashrc breaks standard terminal input |
1,621,502,663,000 |
So, I recently downloaded a cli which shares a lot of commands similar to linux.
Like mega-login : login & mega-logout :logout
and I am too tired of writing mega every time I need to use the cli.
I thought of using alias but I don't want to screw some other program that use the some other command I don't know of.
Like if I create an alias login then what will happen to the system login command? Plus there are a lot of commands in the cli.
So, I thought of using a script, but I didn't know how to do it.
Here what I had in my mind.
So when I use m login or m logout it will search if a command mega-login or mega-logout exists and then call it.
So I tried hours coming up with various functions while learning fish and this is what I wrote.
function m --argument value $argv
echo value $value $argv
if type mega-$value
set MEGA
for temp in $argv
set MEGA $MEGA$temp
echo $MEGA
end
echo MEGA \n\n $MEGA
eval $MEGA
end
end
This still doesn't work.
PS: I wrote this on my first try, but I dropped it once I couldn't figure it out.
function m --argument value $argv
echo value $value $argv
if type mega-$value
set MEGA mega-$argv
echo $argv \n\n\n $MEGA
eval $MEGA
end
end
|
Not a bad first (and second) attempt. It can be tricky to get it just right.
How about:
function m
set -l mega_cmd "mega-$argv[1]"
set -l mega_args $argv[2..]
if type -q "$mega_cmd"
echo "Executing $mega_cmd $mega_args"
"$mega_cmd" $mega_args
end
end
Of course, that's for readability (which I prefer), but it can be condensed down to:
function m
if type -q "mega-$argv[1]"
echo "Executing mega-$argv[1] $argv[2..]"
"mega-$argv[1]" $argv[2..]
end
end
| How do I extract variables from a list in fish? |
1,621,502,663,000 |
I've written the following script, intended to start a daemon and display a Zenity window, then stop the daemon when the window is closed:
#!/usr/bin/fish
if not ps aux | grep [s]erviio > /dev/null
set -x JAVA "/usr/lib/jvm/java-8-openjdk-amd64/jre/bin/java"
~/Programs/serviio/bin/serviio.sh &
zenity --info --text="Serviio is running.\nClick OK to stop." --title="Serviio"
~/Programs/serviio/bin/serviio.sh -stop
end
If I run the script from a terminal it works just fine. It also works from a bash terminal, which seems to show that the shebang is working as expected.
However if I create a launcher to point to the script and try to run it, nothing happens. Serviio doesn't start (I can confirm that from ps aux) and no Zenity window shows.
I've tried to figure out what it is about the script that's causing a problem but haven't had any success.
If I remove the test for whether Serviio is running, the script works.
If I keep the check but make the script display the contents of $JAVA in a Zenity window instead of launching Serviio, it works.
In other words I can't identify any single element in the script that would prevent it from running.
What could be the problem?
|
I found out why by redirecting the output of the ps command to a file. If I run the script from a launcher, grep finds the script itself (which has "serviio" in its name) and so it doesn't execute the code inside "if".
I fixed it by making what grep looks for more specific.
The main cause seems to be that if the script is run directly from a terminal it doesn't appear as a process but if it's run from a launcher then the interpreter (fish in this case) appears with the script as a parameter.
| Why does this fish script does not run from a launcher? |
1,621,502,663,000 |
I'm using Fish shell on Urxvt terminal.
I want to map Ctrl+E as auto-completion key, what is done by pressing Right arrow key by default.
I'm not sure if it's shell's or terminal's feature to do so, but it's clearly not the same as what is done by Tab, and also, I could not find myself such function name in manual of fish's built-in bind command.
|
The binding your looking for is forward-char. Normally the → (right arrow) key and Ctrl-F are bound to it and will accept a fish's suggestion. Note that this is different from an auto-completion, corresponding to complete-and-search and bound to Tab by default.
To add Ctrl-E to this list, you can do:
bind \ce forward-char
| Remap Ctrl+E to autocomplete file names in fish |
1,621,502,663,000 |
I often find myself piping a command's output into less because less is far superior for studying the output than the normal terminal.
While I can always append | less to every command, I was wondering if there is a more concise way of doing this requiring fewer keystrokes.
One option would be to alias less allowing me to type |L instead of |less.
Is there a smarter way? Like binding | less to a certain key combination?
I use fish but answers for zsh and bash are equally welcome, though more generic ones are preferred.
|
One way is a custom key binding. Example:
bind \el "commandline --insert '| less'"
now pressing alt-L or option-L will insert | less at your cursor.
| How to display stdout of command in `less` with as few keystrokes as possible? |
1,621,502,663,000 |
I want to customize my fish shell using the Web UI mode, but when running fish_config colors, the following error is shown.
surface@Surface ~> fish_config starting-colors
Web config started at file:///tmp/web_configoafehdco.html
Hit ENTER to stop.
Start : This command cannot be run due to the error: The system cannot find the file specified.
At line:1 char:1
+ Start "file:///tmp/web_configoafehdco.html"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommandd
I am running Ubuntu in the Windows Subsystem for Linux
|
After going through some articles and not finding the correct answer, I found that when running 'help'
it opens the browser and points to
file://wsl%24/Ubuntu-20.04/usr/share/doc/fish/index.html#variables-for-changing-highlighting-colors
and when we're trying to run fish_config, it points to
"file://wsl%24/Ubuntu/tmp/web_configpo_b9wan.html"
That means, we need to change our wsl%24/Ubuntu to wsl%24/Ubuntu-20.04.
To do so, first of all, open the webconfig directory.
cd /usr/share/fish/tools/web_config
Now, give write permission to the webconfig.py file.
sudo chmod 777 webconfig.py
Modify the following line from "file:///" + f.name" to "file://wsl%24/Ubuntu-20.04" + f.name in webconfig.py file.
Change the file's permission back to its original state by running chmod 644 webconfig.py
You're good to go.
| Error starting the fish_config web ui in WSL |
1,621,502,663,000 |
I use fish shell mainly from Rider IDE and iTerm2.
I've noticed that every task that implies saving something for future sessions will not operate transparently between the two aforementioned contexts.
More precisely if I define a universal exported variable, or an alias, they'll be preserved from the "context" where they were defined and are absent from the other one.
For example, this is the output of alias invoked from Rider IDE (Terminal View):
❯ alias
alias br1 'brightness 1'
alias cat bat
alias cdg 'cd $(git rev-parse --show-cdup)./'
alias l ls
alias ll 'ls -l'
alias ls lsd
alias lt 'lsd -l --tree'
And this is the output of alias invoked from iTerm2:
❯ alias
alias br1 'brightness 1'
alias cat bat
alias ll 'ls -l'
alias ls lsd
The same behaviour with environment variables.
|
The Jetbrains IDEs run fish with a specific environment in order to add their own integrations. They do this by setting $XDG_CONFIG_HOME, which is where fish finds its universal variables.
This is broken in a variety of ways. See https://youtrack.jetbrains.com/issue/IDEA-169111
You might want to disable the shell integration in Preference -> Tools -> Terminal
| fish shell: universal variables and alias not shared between "contexts" |
1,621,502,663,000 |
I was using fish-shell when reading about kill command.
The output of kill -l command for fish is
HUP INT QUIT ILL TRAP ABRT IOT BUS FPE KILL USR1 SEGV USR2 PIPE ALRM
....
When invoking same command in bash I had
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
....
I checked kill with whereis, and there is valid path to program /usr/bin/kill. I also checked man bash for kill, and didn't find anything connected to kill itself :(, so it's not bash builtin.
I also tried kill -l on tcsh and output was once more different.
This is not very important problem for me, but I really curious why does it look like this.
I'm using RHEL7 clone.
|
It can still be a shell built-in even when not documented:
~ (101) bash
tom@vmw-debian7-64:~$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP
6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1
11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM
16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ
26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR
31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3
38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13
48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12
53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7
58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
tom@vmw-debian7-64:~$ type kill
kill is a shell builtin
tom@vmw-debian7-64:~$
With fish:
tom@vmw-debian7-64:~$ fish
Welcome to fish, the friendly interactive shell
Type help for instructions on how to use fish
tom@vmw-debian7-64 ~> kill -l
HUP INT QUIT ILL TRAP ABRT BUS FPE KILL USR1 SEGV USR2 PIPE ALRM TERM STKFLT
CHLD CONT STOP TSTP TTIN TTOU URG XCPU XFSZ VTALRM PROF WINCH POLL PWR SYS
tom@vmw-debian7-64 ~> type kill
kill is /bin/kill
tom@vmw-debian7-64 ~>
With zsh
tom@vmw-debian7-64:~$ zsh
vmw-debian7-64% kill -l
HUP INT QUIT ILL TRAP ABRT BUS FPE KILL USR1 SEGV USR2 PIPE ALRM TERM STKFLT CHLD CONT STOP TSTP TTIN TTOU URG XCPU XFSZ VTALRM PROF WINCH POLL PWR SYS
vmw-debian7-64% type kill
kill is a shell builtin
With tcsh
tom@vmw-debian7-64:~$ tcsh
~ (101) kill -l
HUP INT QUIT ILL TRAP ABRT BUS FPE KILL USR1 SEGV USR2 PIPE ALRM TERM STKFLT
CHLD CONT STOP TSTP TTIN TTOU URG XCPU XFSZ VTALRM PROF WINCH POLL PWR SYS
RTMIN RTMIN+1 RTMIN+2 RTMIN+3 RTMAX-3 RTMAX-2 RTMAX-1 RTMAX
~ (102) type kill
type: Command not found.
~ (103) which kill
kill: shell built-in command.
~ (104) which which
which: shell built-in command.
It is a built-in for dash also, but the listing is a single column...
...
RTMAX-8
RTMAX-7
RTMAX-6
RTMAX-5
RTMAX-4
RTMAX-3
RTMAX-2
RTMAX-1
RTMAX
$ type kill
kill is a shell builtin
$ which kill
/bin/kill
$ /bin/kill -l
HUP INT QUIT ILL TRAP ABRT BUS FPE KILL USR1 SEGV USR2 PIPE ALRM TERM STKFLT
CHLD CONT STOP TSTP TTIN TTOU URG XCPU XFSZ VTALRM PROF WINCH POLL PWR SYS
I would get similar results for other systems (the nice thing about portable code). As for whereis, the manual page says
WHEREIS(1) User Commands WHEREIS(1)
NAME
whereis - locate the binary, source, and manual page files for a com‚Äê
mand
note the binary (it does not try to look for shell built-ins or aliases).
| Why 'kill -l' gives different output in fish and bash |
1,621,502,663,000 |
I recently switched from bash to fish. I like it, but I don't know how to exit, when I enter history. How do I do that?
|
The history function will show your history in your pager program. This can changed by setting the $PAGER variable, but usually it's a program called less.
And to quit that one, press q. Pressing h will show you the help screen.
If it's not less or something similar (most pagers quit with q, to be honest), then it depends on that program.
| Exit 'history' in fish |
1,621,502,663,000 |
With my fish shell, I have defined the alias
alias black='command black -l 110'
When I type black in my shell and start to tab-complete, I get the error
complete: maximum recursion depth reached
The same thing happens with similar aliases such as
alias readelf='command readelf -W'
|
If I enter
alias readelf='command readelf -W'
into a fish shell, this is what fish does with it:
$ type -a readelf
readelf is a function with definition
# Defined via `source`
function readelf --wraps='command readelf -W' --description 'alias readelf=command readelf -W'
command readelf -W $argv;
end
The --wraps argument, which controls completions, looks wrong.
Since fish creates functions for aliases, just create the function yourself:
function readelf --wraps=readelf
command readelf -W $argv
end
Ref: https://fishshell.com/docs/current/cmds/function.html
| fish - Maximum recursion depth reached with tab-complete |
1,621,502,663,000 |
I have a script that prints a string to terminal,
and I want to check value of myScript output.(in this case resultString)
I tried with this method, but it didn't worked.
(for simplicty i replaced my script with echo something so the output is 'something' in this cases.
)
echo something |
if test - = something
echo true
else
echo false
end
# this prints the false while it should be true!
also trying to set the output to a variable, but it didn't worked either.
echo something |
set x -;
if test $x = something
echo true
else
echo false
end
# this prints the false while it should be true!
|
test and set do not understand that - means "read from standard input". Use read instead:
echo something |
read x
if test "$x" = something
echo true
else
echo false
end
| test standard output with fish |
1,621,502,663,000 |
Basically, I'd like to create a file .cd-reminder with an announcement/message inside a specific directory. It will be displayed every time someone 'cd' into that specific directory.
There is a shell script for that already and I'm currently using Fish and not familiar on how to convert it; any help appreciated!
reminder_cd() {
builtin cd "$@" && { [ ! -f .cd-reminder ] || cat .cd-reminder 1>&2; }
}
alias cd=reminder_cd`
|
function cd
builtin cd $argv
and test -f .cd-reminder
and cat .cd-reminder
end
I just realized this will return a non-success exit status when the .cd-reminder file does not exist in a directory. use this instead so the function will only return non-success if you can't cd to the given dir.
function cd
builtin cd $argv
and begin
test -f .cd-reminder
and cat .cd-reminder
or true
end
end
| Bash to Fish Conversion: Display custom message when CD'ing into a specific directory |
1,621,502,663,000 |
How can I access the non-aliased version of a command from within the alias for that command? In bash, I can do something like alias ls='\ls -l' to access the non-aliased ls inside this alias for ls. How can I do this in fish?
Right now I'm using env to get the executable for the command, but is there a better way?
alias man='PAGER="bat -p" /usr/bin/env man'
|
For simple cases, fish's alias will figure it out itself.
You can just do alias ls='ls -l' and it will result in the following function:
function ls --description 'alias ls=ls -l'
command ls -l $argv
end
because
fish's alias is a cheesy wrapper that defines functions
the way to call a command by name, skipping functions and builtins, is to use command
So you can do
alias man='PAGER="bat -p" command man'
(similary, builtin foo calls the builtin "foo", skipping any functions)
In this specific case the best solution is to just set $MANPAGER, skipping the alias entirely:
set -gx MANPAGER "bat -p"
Also, you can avoid any issues with fish's aliases by directly defining a function yourself:
function man
PAGER="bat -p" command man $argv
end
or using an abbreviation instead.
| Fish access non-aliased command from alias |
1,637,322,023,000 |
I can't seem to find any information on how to navigate tab completion or how to bind keys in tab completion in fish shell.
This is what I am trying to achieve but in fish shell rather than zsh. Fish-like argument completion search in ZSH
Please help...
|
The tab completion pager uses the same keys as the rest of the command-line editor, so to bind h to move in the pager (and stay as inserting h when writing a command) use:
bind h 'if commandline --paging-mode; commandline --function backward-char; else; commandline --insert h; end'
Similar lines can be added for j, k, and l.
Note, however, that this breaks while the pager is in search mode (using Ctrl+S) as there is no way of detecting whether search mode is active (that's probably a missing feature).
| How to use hjkl to navigate menu select in fish shell |
1,637,322,023,000 |
I installed Garuda Linux today. The default shell emulator is Alacritty and the default shell, fish. However, after the update to the system, its constantly giving a warning:
Config error: shell: data did not match any variant of untagged enum Program
What is this error and what is causing it?
|
This seems to be a bug in the latest update of alacritty. The issue is still unknown as of today (1st Jan 2021). However, to fix the problem, you simply have to roll-back the alacritty config file located at ~/.config/alacritty/alacritty.yml.
| Error in terminal emulator: Alacritty |
1,637,322,023,000 |
I have some video files in source/ to encode and I want the output to be saved in the local directory, therefore removing source/ in the filename.
I accomplished this by using the following command in fish shell:
$ for file in source/*.mkv
ffmpeg -i "$file" -c:v copy -c:a copy (echo "$file" | sed -e "s/source\///")
end
Although, I find piping the output of echo to sed a bit rudimentary, is there a function that just processes the strings of local variables? Like a sed but just for local variables or filenames.
|
You're removing a (fixed) directory name from the string here.
In standard shell, you can do that with the ${parameter#pattern} expansion, it removes pattern from the start of the string in parameter, so ${file#source/} would remove the prefix source/.
Also in ksh/Bash/zsh ${parameter/pattern} removes the match anywhere in the string, which matches sed's s/pattern// more closely. (${..//..} to remove all matches). Those patterns are the same as the ones used for filename wildcards; they're not regexes.
In fish, there's the builtin string replace command, which seems it can be used here:
> set f source/foobar
> string replace source/ "" -- $f
foobar
or with -r for regex, so we don't need to know the path:
> string replace -r "^.*/" "" -- $f
foobar
(Note that I'm not that familiar with fish. The above seemed to work, but I'm not sure if it breaks in some corner cases.)
| Processing local variable with regular expressions |
1,637,322,023,000 |
I installed debian stretch yesterday. I installed fish shell . I change the default shell to fish by the following
su chsh -s 'which fish'
Then again enter the this command
su chsh -s `which fish`
Now after I restart the PC I encountered the following error while using "su"
sathish@localhost ~> su
Password:
Cannot execute which fish: No such file or directory
|
(Since I'm unable to comment. So posting here)
Change user to su
$ su
(Then enter password)
Type
# chsh [username]
In your case:
# chsh root
Enter login shell /usr/bin/fish
That's it. Logout and login again. Should work
| debian 9 terminal cannot change to su |
1,637,322,023,000 |
I'm trying to understand why the gradle completion isn't applying.
Since gw seems to be a keyword for the completion, I created an alias:
alias gw='./gradlew'
(My project uses gradle wrapper. I don't have gradle installed globally.)
When I type gw <tab> it just does the standard file system completion. I'm expecting something more like when typing git <tab>.
What am I missing?
|
Instead of an alias, use a function, and declare that it wraps gradle
function gw --wraps gradlew
./gradlew $argv
end
See https://fishshell.com/docs/current/cmds/function.html
| Completion for gradle not applying |
1,637,322,023,000 |
i'm trying to set an environment variable EDITOR and change it from default which is /usr/bin/nano but i can't use set -Ux due to this behavior
fish FAQ
How to find out which setting fish inherits from? (so i can change it)
Edit:
/etc/environment is empty
set -S EDITOR
$EDITOR: set in global scope, exported, with 1 elements
$EDITOR[1]: |/usr/bin/nano|
$EDITOR: set in universal scope, exported, with 1 elements
$EDITOR[1]: |/usr/bin/nvim|
$EDITOR: originally inherited as |/usr/bin/nano|
|
In fish, since version 3.6.0, you can ask set --show variable and it will tell you what value fish originally inherited. For example:
> set --show foo
$foo: set in global scope, exported, with 1 elements
$foo[1]: |banana|
$foo: originally inherited as |bar|
This will help you figure out if the value was what fish already got from its parent process at launch, or if it was changed inside of fish.
If your issue is just that things that open an EDITOR open nano, it is entirely possible that nothing actually set an editor and these things default to looking at a list like "nano", "vim", "emacs", "joe" and open the first match. In that case set --show EDITOR would show you nothing.
Or you have it inherited and it's just set in e.g. /etc/bashrc or /etc/profile - distributions often set their default settings in these. Just grep -r EDITOR /etc should show any of these.
If you do have an inherited $EDITOR, and you can't find it in /etc/, there are things you can do, but they are heavily OS-dependent and unportable. Fish isn't the parent process, and you'll need to look at the list of parent processes.
For instance Linux has the /proc/ filesystem where you can find a process' environment in /proc/$pid/environ, with NUL-delimited "var=val" fields.
So you can
get the process' parent pid
look at the parent's environ
go to 1
until you reach a parent pid of 0, which means no parent (this will be init with a pid of 1).
As a quick sketch:
# Start with fish's pid
set -l ppid $fish_pid
# Get the parent pid - ps' output format is fairly terrible and unportable
while set -l ppid (ps -o ppid -p $ppid | string trim)[2]
and test "$ppid" -gt 0
# print the pid and the matching environ value
echo $ppid (sudo grep -z foo /proc/$ppid/environ | string split0)
end
You might get output like:
1305 foo=bar
759
9
8
7
1
This means that the process with pid "1305" had the value "bar" for "foo", and its parents didn't have it in their environ. Note that in this example I set the variable (with export foo=bar) in process 759 - but it didn't have it in its environ since that's the values it has inherited.
So in most cases the process to set it will be the one after the last one with the inherited value.
You can ask ps for information about that process via ps -p 759 (insert your PID as appropriate):
PID TTY TIME CMD
759 pts/0 00:00:00 bash
So in this case a bash process set the variable, and another bash process (1305) inherited it.
| where a variable inherit from, Fishshell |
1,637,322,023,000 |
I'm studying the RBENV codebase, and I see that on line 116 of the rbenv-init file, a function is created which contains a switch statement. My hypothesis is that we check whether the value of the command variable is one of the members of the array of values in the commands (plural) variable. If it is, we execute branch 1 of the switch statement. Otherwise, we execute branch 2.
I wanted to write a simple script to test my hypothesis, so I wrote the following:
#!/usr/bin/env fish
set command "foo"
switch $command
case ${argv[*]}
echo "command in args"
case "*"
echo "command not found"
end
However, when I run this script, I get the following error:
$ ./foo bar baz
./foo (line 6): ${ is not a valid variable in fish.
case ${argv[*]}
^
warning: Error while reading file ./foo
I was expecting argv to evaluate to an array containing bar and baz, since those are the two args I provide to the script. My syntax matches that of line 117 in the source code (i.e. case ${commands[*]}).
The shell I'm executing the script in is zsh v5.8.1, however my shebang specifically references the 'fish' shell so I'd think my shell wouldn't matter. I have fish v3.5.1 installed, fwiw.
|
The bash code in there is:
commands=(`rbenv-commands --sh`)
That's split+glob applied to the output of rbenv-commands --sh and the resulting words assigned to elements of the $commands bash array
case "$shell" in
fish )
cat <<EOS
function rbenv
set command \$argv[1]
set -e argv[1]
switch "\$command"
case ${commands[*]}
rbenv "sh-\$command" \$argv|source
case '*'
command rbenv "\$command" \$argv
end
end
EOS
;;
cat << EOS... outputs some fish code, but as that EOS is not quoted, expansions (by bash) are still performed. Except when there's a backslash in front, $param is expanded by bash. You'll notice that most $s are prefixed with a \, but not ${commands[*]} (which anyway is Korn shell syntax, not fish syntax). That's expanded by bash to the elements of the $commands array joined with the first character of $IFS (space by default).
So the fish code that that cat command produces is rather like:
function rbenv
set command $argv[1]
set -e argv[1]
switch "$command"
case elements of the commands bash array
rbenv "sh-$command" $argv|source
case '*'
command rbenv "$command" $argv
end
end
To check whether a string is among a list, you'd use fish's contains buitin:
set list foo bar baz
set string foo
if contains -- $string $list
echo $string is in the list
end
(like zsh's if (( $list[(Ie)$string] )) or for non-empty lists if [[ $string = (${(~j[|])list}) ]])
You can also do:
switch $string
case $list
echo $string matches at least one of the patterns in the list
end
(which is not the same unless none of the elements of the list contain * or ? characters)
(that's more like zsh's [[ $string = (${(j[|])~list}) ]] (for non-empty lists)).
There's also:
if string match -q -- $pattern $list > /dev/null
echo at least one of the elements of the list matches $pattern
end
(like zsh's if (( $list[(I)$pattern] ))).
| Fish shell - syntax for creating a switch statement which checks against an array of values |
1,637,322,023,000 |
I have a few abbreviations that I want to run on one command.
Let's say given this config:
abbr command1 "echo 1"
abbr command2 "echo 2"
abbr command3 "echo 3"
I want another abbr that runs all of them together:
abbr allCommands "command1; command2; command3"
But I get
fish: Unknown command: command1
How could I run all of them together?
|
Fish abbreviations are expanded only at the commandline when pressing Space or Enter.
It sounds like you want an alias. Just replace abbr with alias in each of your commands above, and it should work as you expect.
| fish - Run multiple abbreviations with another abbreviation |
1,637,322,023,000 |
I'm working on a completion script for a command, and I'm stuck. The docs and various websites I find don't fit what I need. The main command is pacstall and it has the flags: -I -S -R -C -U -V -L -Up -Qd -Qi. For most of the flags, I need the completions to be the output of a command (if I ran pacstall -I, then tabbed, it would show the output of the command curl -s $(cat /usr/share/pacstall/repo/pacstallrepo.txt)/packagelist. This is what I have so far:
set -l pacstall_commands "-I -S -R -C -U -V -L -Up -Qd -Qi"
complete -f --command pacstall -n "not __fish_seen_subcommand_from $pacstall_commands" -a -I -d 'Install package'
complete -f --command pacstall -n "not __fish_seen_subcommand_from $pacstall_commands" -a -S -d 'Search for package'
complete -f --command pacstall -n "not __fish_seen_subcommand_from $pacstall_commands" -a -R -d 'Remove package'
complete -f --command pacstall -n "not __fish_seen_subcommand_from $pacstall_commands" -a -C -d 'Change repository'
complete -f --command pacstall -n "not __fish_seen_subcommand_from $pacstall_commands" -a -U -d 'Update pacstall scripts'
complete -f --command pacstall -n "not __fish_seen_subcommand_from $pacstall_commands" -a -V -d 'Print pacstall version'
complete -f --command pacstall -n "not __fish_seen_subcommand_from $pacstall_commands" -a -L -d 'List packages installed'
complete -f --command pacstall -n "not __fish_seen_subcommand_from $pacstall_commands" -a -Up -d 'Upgrade packages'
complete -f --command pacstall -n "not __fish_seen_subcommand_from $pacstall_commands" -a -Qd -d 'Query the dependencies of a package'
complete -f --command pacstall -n "not __fish_seen_subcommand_from $pacstall_commands" -a -Qi -d 'Get package info'
Also the script keeps tab completing even after typing in the flag
|
The -n flag of the complete command allows you to specify a condition for the completion to occur. In this case, you can use the __fish_seen_subcommand_from function to specify whether the subcommand -I has been seen already.
After this, you can specify with the -a flag the command you want to run in ().
complete -f --command pacstall -n "__fish_seen_subcommand_from -I" -a "(curl -s (cat /usr/share/pacstall/repo/pacstallrepo.txt)/packagelist)"
As a note, in fish, you don't use the $ symbol when capturing the result of a command as you posted in your question.
As for your final point at the end. If you remove the quotes from the set, that should solve the issue of the duplicates. By using quotes in that fashion, it specifies one long command rather than separate ones.
| Fish completion script |
1,637,322,023,000 |
Trying fish, I am stuck on equivalents for some of the variable expansions from bash:
x=${this:-$that}
x=${this:-that}
How do I do that in fish?
|
Nothing so short as that posix shell variable expansion:
if set -q this; or test -z $this
set x $that
else
set x $this
end
or the "terse" version
begin; set -q this; or test -z $this; end; and set x $that; or set x $this
(I'll be happy to be proven wrong about this one)
| fish equivalent of ${this:-that} expansion and similar |
1,637,322,023,000 |
In bash I can do:
foo() { echo bar; }
export -f foo
perl -e 'system "bash -c foo"'
I can also access the function definition:
perl -e 'print "foo".$ENV{"BASH_FUNC_foo%%"}'
How do I do the same in fish?
Edit:
With this I can get the function definition:
functions -n | perl -pe 's/,/\n/g' | while read d; functions $d; end
If I can put that in an enviroment variable accessible from Perl, I ought to be able to execute that before executing the command. So similar to:
setenv funcdefs (functions -n | perl -pe 's/,/\n/g' | while read d; functions $d; end)
perl -e 'system($ENV{"funcdefs"},"foo")'
But it seems setting funcdefs ignores the newlines: $ENV{"funcdefs"} is one horribly long line.
The odd part is that it seems fish does support environment variables containing newlines:
setenv newline 'foo
bar'
echo "$newline"
Can I encourage fish to put the output from the command into a variable, but keeping the newlines?
|
Ugly as hell, but works:
function foo
echo bar;
end
setenv funcdefs (functions -n | perl -pe 's/,/\n/g' | while read d; functions $d; end|perl -pe 's/\n/\001/')
perl -e '$ENV{"funcdefs"}=~s/\001/\n/g;system ("fish", "-c", $ENV{funcdefs}."foo")'
| Accessing fish functions from perl |
1,637,322,023,000 |
At work we use the Environment Modules package (and hence modulecmd) extensively.
man module includes the sentence “The sh, csh, tcsh, bash, ksh, and zsh shells are supported by modulecmd.” This is confirmed by
hgs15624@pc0072 /d/w/c/m/m/mml> modulecmd fish load matlab
init.c(379):ERROR:109: Unknown shell type 'fish'
I don't really understand the why this is. Which of modulecmd or fish would have to change?
I deduce from my experiments that I can't sensibly use module with fish. Am I correct?
|
It looks like Modules needs to be extended to support fish; none of the existing shells are close enough to easily apply to fish.
| Can I use modulecmd with fish shell? |
1,637,322,023,000 |
In bash you would do
touch "foo bar"
rm "$(echo foo bar)"
How would you do that in fish?
This doesn't work for obvious reasons:
touch "foo bar"
rm "(echo foo bar)"
|
Seems that without the quotes produces the desired output:
touch "foo bar"
rm (echo foo bar)
A test:
echo "foo bar" > foo
touch "foo bar"
rm (cat foo)
| Quoting command substituted value |
1,637,322,023,000 |
I would like to use systemd to accomplish this if possible. This is what I have done so far.
Wrote a script in fish that will stage, commit and push files to a repository. Script made executable with chmod u+x <script>.fish.
Wrote a service unit.
Reloaded with systemctl --user daemon-reload, enabled with systemctl --user enable backup.service.
This is the fish script.
#!/usr/bin/fish
set note_dir /home/yjh/Documents/notes
cd $note_dir
set today (date "+(%A) %B-%d-%G %T")
git add .
git commit -am $today
git push origin master
This is the service unit file.
[Unit]
Description=Backup obsidian notes before shutdown
DefaultDependencies=no
After=network-online.target
Wants=network-online.target
Before=halt.target reboot.target shutdown.target
[Service]
Type=oneshot
RemainAfterExit=true
ExecStop=fish /home/yjh/scripts/backup.fish
[Install]
WantedBy=halt.target reboot.target shutdown.target
This is the service unit file after I applied the link to the answer provided by Freddy. That answer linked to another answer and I also applied those changes but it still didn't work.
I have ran the script in two ways manually with ./<script>fish and through starting it with systemctl like this systemctl --user start backup.service and they both are able to push my code to github. I have already setup SSH for that specific repository, so, no password or username is asked when I want to push to github.
|
TL;DR, try this simplified version:
[Unit]
Description=Backup obsidian notes before shutdown
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStop=fish /home/yjh/scripts/backup.fish
[Install]
WantedBy=default.target
Running this as a user service, my test script was not automatically started (inactive (dead) instead of active (exited)). At first I used WantedBy=multi-user.target in the install section. But this target is not available running user services, same as the halt.target or reboot.target. Switching it to WantedBy=default.target made the difference, see Systemd service does not start (WantedBy=multi-user.target).
Removing DefaultDependencies=no adds implicit dependencies Conflicts=shutdown.target and Before=shutdown.target, see systemd.target and systemd.special#shutdown.target.
Reenable the service after editing it to change the symlinks:
systemctl --user reenable backup.service
Then reboot and shutdown again to see if it works.
| Unable to run git commands before shutdown |
1,637,322,023,000 |
I'm using complete -c cl -o editz -f -xa '(cl -autocomplete 15 | sed "s/:/\\t/" | sed -r "s/^(.{60}).*/\1/")' to dynamically feed the latest 15 entires in a log program to fish for tab-completion. It works very well but I'd like to style how fish presents them. I'd like to avoid the two columns and left-align the description text.
I assume there is a function that defines how complete -xa handles the incoming list. Where (which file) is this definition located and is it possible to alter how this list is presented?
|
I'd like to avoid the two columns and left-align the description text.
Neither of these are configurable in fish.
I assume there is a function that defines how complete -xa handles the incoming list.
There isn't a script function that defines how this is handled. It's all hard-coded in C++. Should be in https://github.com/fish-shell/fish-shell/blob/master/src/pager.cpp
| Where is the default fish completion style defined or how do I style the fish completion options listing? |
1,637,322,023,000 |
If I try to get the output (stdout) of a python program into a variable I do this:
set zpath (python something.py "$argv")
But if the program spawns a curses interface, it won't show.
The program displays a curses interface temporarily to select something, it exits the curses before the program ends. It prints something to stdout which is the useful data.
I read that I can I add 2>&1 >/dev/tty to the end of the command.
That does make the curses interface show but the output is not saved to the variable.
If I print something to test, it just prints it to the shell instead of into the variable.
How can I make the curses interface work, but also the stdout capture work?
I'm specially looking for a simple solution since the redirections to /dev/tty look messy,
and I need to make it work for different shells.
|
I read that I can I add 2>&1 >/dev/tty to the end of the command.
This redirects stdout to the terminal (and stderr to where stdout originally went - the command substitution buffer).
If that shows the interface, and running it without redirections doesn't, that means the program uses stdout to display it.
That means, if
It prints something to stdout which is the useful data.
That output will also end up at the terminal.
I'm afraid if the program wants to use a tty on stdout to display its interface and then print the useful output to that same file descriptor, to stdout, then you can't redirect these two things separately. The shell can't separate them because they aren't separate.
What you would have to do is to modify the program so that it displays its interface on one file like /dev/tty, and print the useful output to another, like stdout.
This is also how fzf, which does open an interactive terminal interface and print something to stdout, operates - on unix it opens /dev/tty - see https://github.com/junegunn/fzf/blob/ef67a45702c01ff93e0ea99a51594c8160f66cc1/src/tui/light_unix.go#L50-L63 and https://github.com/junegunn/fzf/blob/b3ab6311c587e18ee202c5205afc658a33f2a23c/src/tui/light.go#L29
Or it could put the display on stdout and print the useful information on stderr - that would make that 2>&1 >/dev/tty trick work.
Sidenote:
set zpath (python something.py "$argv")
In fish, you most likely do not want to quote that $argv - if it's set to multiple arguments you've now squashed them together into something nonsensical. It also won't help with e.g. spaces because fish does not perform word splitting like bash does. Once a variable has been set to X elements expanding it outside of quotes expands it to those X elements without splitting them apart again.
| Get output of a command that uses curses |
1,637,322,023,000 |
So I am running terminator 0.98. I like fish shell but for some task it is handy to have bash (like for virtualenvwrapper). So I now have two windows that open when I start terminator. But I would like to have one that opens with fish and one with bash. Is this possible, if so: how?
I start terminator with my custom layout by changing my config file located ~/.config/terminator/config.
In the layout section of the config file I used this code.
[layouts]
[[default]]
[[[child0]]]
fullscreen = False
last_active_window = True
maximised = True
order = 0
parent = ""
size = 1280, 985
type = Window
[[[child1]]]
order = 0
parent = child0
position = 490
ratio = 0.5
type = VPaned
|
You need to add a command to the relevant pane. If your default shell is bash, just have one pane run fish:
[layouts]
[[default]]
[[[child0]]]
fullscreen = False
last_active_window = True
maximised = True
order = 0
parent = ""
size = 1280, 985
type = Window
[[[child1]]]
order = 0
parent = child0
command = 'bash'
position = 490
ratio = 0.5
type = VPaned
[[[child1]]]
order = 0
parent = child0
position = 490
ratio = 0.5
type = VPaned
| Can I open terminator with one windows with bash and another with fish? [duplicate] |
1,637,322,023,000 |
I am using fish as shell, ssh shortcut function as following:
function sshec2
ssh -i $HOME/.ssh/key.pem -t -t "ubuntu@$argv[1]"
end
To ssh into specific AWS EC2 instance, I wrote command pipe flow:
ec2-describe-instances --region us-west-2 --filter "tag:Name=test-box" |
grep 'INSTANCE' |
grep -E -m 1 -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'|
head -1 |
sshec2
However I got an error ssh: connect to host port 22: Connection refused, while sshec2 function works when I run sshec2 <ec2_public_ip>.
Any stupid part I am missing?
|
If I understand correctly, you have a pipeline that generates a list of host names (ec2-describe-instances … | grep … | grep …), you take the first line (head -1), and you want to use that as the host name to connect to. You're passing the host name on the standard input of the sshec2 function and calling the function with no argument. So when the function is executed, $argv[1] is empty, and you end up running ssh with the arguments -i, /home/dearrrfish/.ssh/key.pem, -t, -t, ubuntu@. If you ended up with a valid ssh command line and the connection did go through, then the output of the … | head -1 pipeline would be piped into the program that ssh runs.
You need to pass the host name as the first argument to the function instead. The tool for that is command substitution.
sshec2 (ec2-describe-instances --region us-west-2 --filter "tag:Name=test-box" |
grep 'INSTANCE' |
grep -E -m 1 -o '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' |
head -1)
| Scripting SSH function getting `Connection refused` error |
1,637,322,023,000 |
Before switching to fish shell, I frequently used various commands in zsh with which some_command. An example might be:
$ file `which zsh`
/opt/local/bin/zsh: Mach-O 64-bit executable arm64
/bin/zsh: Mach-O universal binary with 2 architectures: [x86_64:Mach-O 64-bit executable x86_64
- Mach-O 64-bit executable x86_64] [arm64e:Mach-O 64-bit executable arm64e
- Mach-O 64-bit executable arm64e]
/bin/zsh (for architecture x86_64): Mach-O 64-bit executable x86_64
/bin/zsh (for architecture arm64e): Mach-O 64-bit executable arm64e
When I try to do this with fish it fails:
$ which zsh
/opt/local/bin/zsh
$ file `which zsh`
`which: cannot open ``which' (No such file or directory)
zsh`: cannot open `zsh`' (No such file or directory)
Any idea of why this doesn't work fish as opposed to other more bash-like shells?
|
fish does not use backticks for command substitutions. Instead one can use parens: file (which zsh) or (in release 3.4.0 and later) file $(which zsh). These mean the same thing.
Check out fish for bash users for other differences.
| fish shell: why does `file `which command`` work in zsh and bash, but not fish? |
1,637,322,023,000 |
I have a bunch of dotfiles that allow me to have a pretty theme on my terminal and tmux on my local host. I use kitty, fish and tmux. To properly define colors and have a global coherence, I use the following files :
.Xresoures
kitty.conf
fish_prompt.fish
.tmux.conf
On my local host, everything looks really clean :
I also have a remote server, which runs the same arch + fish + tmux and uses exactly the same dotfiles. However, when SSH-ing into the server, everything looks completely different :
I have google around and there are a lot of tutorials that tell you to add a bunch of weird configs, but none actually explain what is really happening under the hood (also, as you can see, none of them worked).
Here is what I tried to do to make it work (without really understanding why) :
Added to tmux.conf :
set^[[3m -g default-terminal "xterm-kitty"
set-option^[[3m -ga terminal-overrides ",xterm-kitty*:Tc"
Added the xterm-kitty terminfo file
Change the TERM env variable to xterm-kitty on login
I would love for some resources to point to how this all works! Thanks!
Edit :
For clarity, here are the values of TERM I have :
On local host : xterm-kitty
On local host inside tmux : xterm-256color
On remote host directly after opening ssh : xterm-kitty
On remote host in tmux : xterm-256color
All files are synced using a git repo, all versions are identical. I have transfered the same terminfo file related to xterm-kitty on both hosts. Also, using this script, I can see that all colors are properly displayed and identical on both hosts.
I also noticed that logging into the remote machine without tmux yields yet another combination of colors (same fish config file used everywhere) :
|
Managed to fix it! It was a combination of all the answers given, with one important extra variable.
Required steps :
Ensuring the TERM variables used are the same on every host and inside every tmux (I ended up using xterm-kitty on the hosts directly and tlux-256color inside the TMUX sessions). Thanks to Nicholas Marriott.
add Tc; to the infocmp of the terminals I use, using this snippet provided by Thomas Dickey :
infocmp -x tmux-256color >foo
printf '\tTc,\n' >>foo
tic -x foo
Add set -g fish_term24bit 1 to my config.fish in order to force fish to use trucolor mode.
| TMUX and terminal colors are not the same locally and over ssh |
1,637,322,023,000 |
Following on from my previous question I tried to run ls -l; and grep html; which did what I wanted however the command didn't exit back to the prompt. Instead it appeared to be waiting for something else to happen and I had to Ctrl+C to end the process.
Can anyone explain why this happened and what the correct syntax for my command would be?
What I'm trying to do is have grep filter the output of the ls -l
|
You probably wanted to pipe ls -l into grep, for which fish uses a pipe character the same as other shells (for once):
ls -l | grep html
This is the same thing you would have written in Bash. Otherwise, grep is filtering your input from the terminal instead.
| Why does the command not exit smoothly? |
1,637,322,023,000 |
I have a bash script which cats a heredoc string, and I'm running it inside a fish shell and then piping it to a source call, like so:
~/foo/baz:
1 #!/usr/bin/env bash
2
3 cat << EOS
4 function bar
5 echo 'Hello world'
6 end
7 EOS
From the fish shell:
richiethomas@richie ~/foo (master) [126]> ./baz | source
richiethomas@richie ~/foo (master)> bar
Hello world
As shown above, this results in the function bar being callable when I run ./baz | source.
However, I get an error when I change the implementation of the bar function to the following:
1 #!/usr/bin/env bash
2
3 cat << EOS
4 function bar
5 set myVar 5
6 switch $myVar
7 case 4
8 echo '4'
9 case 5
10 echo '5'
11 case '*'
12 echo 'Not found'
13 end
14 end
15 EOS
When I try to source this, I get the following error:
richiethomas@richie ~/foo (master) [0|1]> ./baz | source
- (line 1): Missing end to balance this function definition
function bar
^
from sourcing file -
source: Error while reading file '<stdin>'
An equivalent function + switch statement works fine when I paste it directly in the fish shell:
richiethomas@richie ~/foo (master) [0|1]> function bar
set myVar 5
switch $myVar
case 4
echo 'it is 4!'
case 5
echo 'it is 5!'
case '*'
echo 'not found'
end
end
richiethomas@richie ~/foo (master)> bar
it is 5!
I have the same # of end statements in both the baz file and the code I copy/pasted into the shell, so I suspect the error statement is a red herring? If so, I don't know what the real error could be.
My goal is to be able to construct a fish function inside the heredoc string of a bash script, then source that bash script from a fish script so that I can call that function. Where did I go wrong here?
|
Variables ($myVar) get expanded in heredocs, unless you quote it:
cat << 'EOS'
# .....^...^
Ref
3.6.6 Here Documents
| Fish shell - what's wrong with this syntax? |
1,637,322,023,000 |
When I start fish, it prints:
Welcome to fish, the friendly interactive shell
Type `help` for instructions on how to use fish
And then the prompt.
I've actually used fish for a while so I don't need this welcome message. How can I disable it?
|
this has already been answered here but tldr youll want to use the command set -U fish_greeting ""
you can customise the welcome prompt too by typing what you want in the double quotes e.g set -U fish_greeting "üêü"
| Fish shell: How to disable help message? |
1,637,322,023,000 |
as above.
basically I want to implement something like
if not match then
do these things
else
do these other things
fi
Thanks
|
It depends on what you mean by match, but if you mean "exactly match", you can use the string match builtin with a plain argument.
if not string match --quiet -- "some_string" $some_argument
echo no match
else
echo match
end
To match within a string, you can use a glob in some_string, or a regular expression with string match --regex.
| Fish 3.3.1 shell: how do I negate the results of a string match? |
1,637,322,023,000 |
I am currently trying to install fish on a new CentOS 7 machine.
Followed the very straightforward guide which was:
cd /etc/yum.repos.d/
wget https://download.opensuse.org/repositories/shells:fish:release:2/CentOS_7/shells:fish:release:2.repo
yum install fish
But when I run yum install fish I get the output:
No package fish available.
Error: Nothing to do
In /etc/yum.repos.d/ the repo shells:fish:release:2.repo is there.
Is there any reason that yum wouldn't be finding the package?
|
I would suggest you install fish from the EPEL repository for CentOS/Redhat instead.
sudo yum install epel-release
Then if you try sudo yum list fish you should see it.
I know this isn't the answer to what you're asking, but I think it's the way to do what you're trying to accomplish.
| Yum not finding packages from added repo [CentOS 7] |
1,637,322,023,000 |
I have 3 files
Original.js
Original.vue
Original.css
How can I easily copy them to
Copy.js
Copy.vue
Copy.css
Until now, i always just copied one by one, but if I could use something like copy Original.* Copy.*, that would be awesome.
I use the fish shell, if that changes anything.
|
Using string replace
for file in Original.*
cp $file (string replace Original Copy $file)
end
| Copy files with different extensions to different basename with same extensions |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.