date int64 1,220B 1,719B | question_description stringlengths 28 29.9k | accepted_answer stringlengths 12 26.4k | question_title stringlengths 14 159 |
|---|---|---|---|
1,517,332,876,000 |
I use netcat to do the traffic forwarding during 3 machine(A->B->C) ssh tunneling. The proxy command from host A running on host B is like:
/usr/bin/ssh host_B nc localhost 19999
And there exists a tunnel between host_B:19999 and host_C:22
I would like to know what has been done by netcat. Where is the netcat log file? I tried to issue the below proxy command on A:
/usr/bin/ssh host_B nc -vv localhost 19999 > log.txt 2>&1
But it always gives me "ssh_exchange_identification: Connection closed by remote host" on host A
Thanks,
|
Netcat doesn't log anything.
Redirecting the output of netcat to a file breaks your setup because that output is supposed to go to the ssh process. With the redirection you set up, the data sent by the remote host ends up in log.txt instead of being sent to the client. If you only want to log errors, use 2>log.txt.
If you want to dump all the data transmitted by netcat to a file, you need to duplicate it.
unbuffer tee input.data | nc localhost 19999 | unbuffer tee output.data
| How to check the log of netcat during ssh tunnel |
1,517,332,876,000 |
I use nc as part of a verification script, and check the output of each nc command listed against what the expected output should be.
e.g.,
nc -zvw1 serv1.host.com 443 | gawk '{print $7}'
Expected output: succeeded!
The problem I'm facing is if I want to check a range of ports, while some tests may in fact return succeeded!, there's no guarantee that all ports returned as such. This is an issue for me because I compare cmd:output on a 1:1 basis, based off a configuration file that lists the commands and the expected output.
Instead of listing something like:
nc -zvw1 serv1.host.com 443 | gawk '{print $7}'
nc -zvw1 serv1.host.com 444 | gawk '{print $7}'
nc -zvw1 serv1.host.com 445 | gawk '{print $7}'
Expected result: succeeded!
Expected result: succeeded!
Expected result: succeeded!
I'd like to be able to force nc to fail if any ports in the range fail; so in this case my configuration could be condenced to:
nc -zvw1 serv1.host.com 443-445 | gawk '{print $7}'
Expected result: succeeded!
This is a long-winded description of a straight-forward question, unfortunately. Apologies.
|
This could probably work:
seq 443 445 \
| xargs -n1 sh -c 'nc -zvw1 serv1.host.com $0 >/dev/null 2>&1 || (echo error! && exit 255)' 2>/dev/null \
&& echo succeeded!
It basicly emulates port ranges with seq and xargs and utilizes nc's return value to either echo error! and setting exit 255 to abort xargs or echo succeeded! when it successfully connected to each given port number.
| Can you force netcat to succeed only if all ports in port range succeed? |
1,517,332,876,000 |
I tried to make server client model as below
on one shell
nc -l -p 8080 this works as a server
and on another
nc 127.0.0.1 8080 and this works as a client
all of this is fine ... the problem that if I closed the client the server closes also .. how can I keep server working after terminating client ??
|
netcat has a -k option that does what the OP wanted a year ago:
From the man pages:
-k Forces nc to stay listening for another connection after its
current connection is completed. It is an error to use this option with‐
out the -l option.
So this should work:
nc -lk -p 8080
| net cat client and server model |
1,517,332,876,000 |
Currently I'm using the standard netcat -e /bin/sh to provide a remote shell for other computers to access.
The problem is however that this shell is rather terrible, since it has limited output. For example if I send some invalid command xxxxx, I will get no response from the machine, but on the machine there will be an error in the terminal saying /bin/sh: xxxxx: not found.
If I use the shell to launch a console application, often I cannot see anything the console application outputs, and I can't Ctrlz over the shell because that will close netcat on the machine. It's a mess, I'd like it to work just like SSH (which I can't use).
Instead of piping everything to /bin/sh like I'm doing with netcat, would it be possible to create a custom application instead that will show me all the outputs in a terminal? Is it possible somehow get the text off the terminal, regardless of what process wrote to it?
Would it be possible to start an sshd on the box, and then netcat -e "ssh root@localhost" and do it that way? (I've tried this, doesn't seem to work).
I'm looking for any kind of solution.
|
Creating a "custom application" would be re-implementing telnet / ssh. This is, of course, possible, but not necessary.
If there is sshd (or telnetd) on the host you can start it from your netcat-shell session with e.g. /usr/sbin/sshd -p <port> -D 2>&1 and then do ssh -p <port> root@<host> on your client. You might need to add further options to sshd, perhaps create a config file and give it in the command line: /usr/sbin/sshd -f <config-file> ...
If not, you can use the netcat session to upload telnetd or sshd, set up the needed environment / config and run it on some port.
You can also make a wrapper around your shell to redirect stderr to stdout, like /bin/sh 2>&1, which would allow you to see stderr in your netcat session, but would not give you "real terminal" functionality.
Another option is DISPLAY=<client>:0 xtrem if you have xterm or equivalent on the host and X Server on the client.
| Getting more output from NetCat |
1,517,332,876,000 |
I have this nginx custom configuration:
server {
listen 8080;
server_name subdomain.domain.my.id;
location /vless-ws { # Consistent with the path of V2Ray configuration
if ($http_upgrade != "websocket") { # Return 404 error when WebSocket upgrading negotiate failed
return 404;
}
proxy_redirect off;
proxy_pass http://127.0.0.1:19002;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
Here is long option for websocat:
(base) isysrg@isysresearch:~/tmp$ ./websocat --help=long option
websocat 1.12.0
Vitaly "_Vi" Shukela <[email protected]>
Command-line client for web sockets, like netcat/curl/socat for ws://.
USAGE:
websocat ws://URL | wss://URL (simple client)
websocat -s port (simple server)
websocat [FLAGS] [OPTIONS] <addr1> <addr2> (advanced mode)
FLAGS:
--stdout-announce-listening-ports [A] Print a line to stdout for each port being listened
--async-stdio [A] On UNIX, set stdin and stdout to nonblocking mode instead of
spawning a thread. This should improve performance, but may break other
programs running on the same console.
--compress-deflate [A] Compress data coming to a WebSocket using deflate method. Affects
only binary WebSocket messages.
--compress-gzip [A] Compress data coming to a WebSocket using gzip method. Affects only
binary WebSocket messages.
--compress-zlib [A] Compress data coming to a WebSocket using zlib method. Affects only
binary WebSocket messages.
--dump-spec [A] Instead of running, dump the specifiers representation to stdout
-e, --set-environment Set WEBSOCAT_* environment variables when doing exec:/cmd:/sh-c:
Currently it's WEBSOCAT_URI and WEBSOCAT_CLIENT for
request URI and client address (if TCP)
Beware of ShellShock or similar security problems.
-E, --exit-on-eof Close a data transfer direction if the other one reached EOF
--foreachmsg-wait-read [A] Wait for reading to finish before closing foreachmsg:'s peer
--jsonrpc Format messages you type as JSON RPC 2.0 method calls. First word
becomes method name, the rest becomes parameters, possibly automatically
wrapped in [].
--jsonrpc-omit-jsonrpc [A] Omit `jsonrpc` field when using `--jsonrpc`, e.g. for Chromium
--just-generate-key [A] Just a Sec-WebSocket-Key value without running main Websocat
--linemode-strip-newlines [A] Don't include trailing \n or \r\n coming from streams in WebSocket
messages
-0, --null-terminated Use \0 instead of \n for linemode
--no-line [A] Don't automatically insert line-to-message transformation
--no-exit-on-zeromsg [A] Don't exit when encountered a zero message. Zero messages are used
internally in Websocat, so it may fail to close connection at all.
--no-fixups [A] Don't perform automatic command-line fixups. May destabilize
websocat operation. Use --dump-spec without --no-fixups to discover what
is being inserted automatically and read the full manual about Websocat
internal workings.
--no-async-stdio [A] Inhibit using stdin/stdout in a nonblocking way if it is not a tty
-1, --one-message Send and/or receive only one message. Use with --no-close and/or -u/-U.
--oneshot Serve only once. Not to be confused with -1 (--one-message)
--print-ping-rtts Print measured round-trip-time to stderr after each received WebSocket
pong.
--exec-exit-on-disconnect [A] Make exec: or sh-c: or cmd: immediately exit when connection is
closed, don't wait for termination.
--exec-sighup-on-stdin-close [A] Make exec: or sh-c: or cmd: send SIGHUP on UNIX when input is
closed.
--exec-sighup-on-zero-msg [A] Make exec: or sh-c: or cmd: send SIGHUP on UNIX when facing incoming
zero-length message.
-q Suppress all diagnostic messages, except of startup errors
--reuser-send-zero-msg-on-disconnect [A] Make reuse-raw: send a zero-length message to the peer when some
clients disconnects.
-s, --server-mode Simple server mode: specify TCP port or addr:port as single argument
-S, --strict strict line/message mode: drop too long messages instead of splitting
them, drop incomplete lines.
--timestamp-monotonic [A] Use monotonic clock for `timestamp:` overlay
-k, --insecure Accept invalid certificates and hostnames while connecting to TLS
--udp-broadcast [A] Set SO_BROADCAST
--udp-multicast-loop [A] Set IP[V6]_MULTICAST_LOOP
--udp-oneshot [A] udp-listen: replies only one packet per client
--udp-reuseaddr [A] Set SO_REUSEADDR for UDP socket. Listening TCP sockets are always
reuseaddr.
--uncompress-deflate [A] Uncompress data coming from a WebSocket using deflate method.
Affects only binary WebSocket messages.
--uncompress-gzip [A] Uncompress data coming from a WebSocket using deflate method.
Affects only binary WebSocket messages.
--uncompress-zlib [A] Uncompress data coming from a WebSocket using deflate method.
Affects only binary WebSocket messages.
-u, --unidirectional Inhibit copying data in one direction
-U, --unidirectional-reverse Inhibit copying data in the other direction (or maybe in both directions
if combined with -u)
--accept-from-fd [A] Do not call `socket(2)` in UNIX socket listener peer, start with
`accept(2)` using specified file descriptor number as argument instead
of filename
--unlink [A] Unlink listening UNIX socket before binding to it
-V, --version Prints version information
-v Increase verbosity level to info or further
-b, --binary Send message to WebSockets as binary messages
-n, --no-close Don't send Close message to websocket on EOF
--websocket-ignore-zeromsg [A] Silently drop incoming zero-length WebSocket messages. They may
cause connection close due to usage of zero-len message as EOF flag
inside Websocat.
-t, --text Send message to WebSockets as text messages
--base64 Encode incoming binary WebSocket messages in one-line Base64 If
`--binary-prefix` (see `--help=full`) is set, outgoing WebSocket
messages that start with the prefix are decoded from base64 prior to
sending.
--base64-text [A] Encode incoming text WebSocket messages in one-line Base64. I don't
know whether it can be ever useful, but it's for symmetry with
`--base64`.
OPTIONS:
--socks5 <auto_socks5>
Use specified address:port as a SOCKS5 proxy. Note that proxy authentication is not supported yet. Example:
--socks5 127.0.0.1:9050
--autoreconnect-delay-millis <autoreconnect_delay_millis>
[A] Delay before reconnect attempt for `autoreconnect:` overlay. [default: 20]
--basic-auth <basic_auth>
Add `Authorization: Basic` HTTP request header with this base64-encoded parameter
--queue-len <broadcast_queue_len>
[A] Number of pending queued messages for broadcast reuser [default: 16]
-B, --buffer-size <buffer_size> Maximum message size, in bytes [default: 65536]
--byte-to-exit-on <byte_to_exit_on>
[A] Override the byte which byte_to_exit_on: overlay looks for [default: 28]
--client-pkcs12-der <client_pkcs12_der> [A] Client identity TLS certificate
--client-pkcs12-passwd <client_pkcs12_passwd>
[A] Password for --client-pkcs12-der pkcs12 archive. Required on Mac.
--close-reason <close_reason>
Close connection with a reason message. This option only takes effect if --close-status-code option is
provided as well.
--close-status-code <close_status_code> Close connection with a status code.
-H, --header <custom_headers>...
Add custom HTTP header to websocket client request. Separate header name and value with a colon and
optionally a single space. Can be used multiple times. Note that single -H may eat multiple further
arguments, leading to confusing errors. Specify headers at the end or with equal sign like -H='X: y'.
--server-header <custom_reply_headers>...
Add custom HTTP header to websocket upgrade reply. Separate header name and value with a colon and
optionally a single space. Can be used multiple times. Note that single -H may eat multiple further
arguments, leading to confusing errors.
--exec-args <exec_args>...
[A] Arguments for the `exec:` specifier. Must be the last option, everything after it gets into the exec
args list.
--header-to-env <headers_to_env>...
Forward specified incoming request header to H_* environment variable for `exec:`-like specifiers.
-h, --help <help>
See the help.
--help=short is the list of easy options and address types
--help=long lists all options and types (see [A] markers)
--help=doc also shows longer description and examples.
--inhibit-pongs <inhibit_pongs>
[A] Stop replying to incoming WebSocket pings after specified number of replies
--just-generate-accept <just_generate_accept>
[A] Just a Sec-WebSocket-Accept value based on supplied Sec-WebSocket-Key value without running main
Websocat
--max-messages <max_messages>
Maximum number of messages to copy in one direction.
--max-messages-rev <max_messages_rev>
Maximum number of messages to copy in the other direction.
--conncap <max_parallel_conns>
Maximum number of simultaneous connections for listening mode
--max-sent-pings <max_sent_pings>
[A] Stop sending pings after this number of sent pings
--max-ws-frame-length <max_ws_frame_length>
[A] Maximum size of incoming WebSocket frames, to prevent memory overflow [default: 104857600]
--max-ws-message-length <max_ws_message_length>
[A] Maximum size of incoming WebSocket messages (sans of one data frame), to prevent memory overflow
[default: 209715200]
--origin <origin> Add Origin HTTP header to websocket client request
--pkcs12-der <pkcs12_der>
Pkcs12 archive needed to accept SSL connections, certificate and key.
A command to output it: openssl pkcs12 -export -out output.pkcs12 -inkey key.pem -in cert.pem
Use with -s (--server-mode) option or with manually specified TLS overlays.
See moreexamples.md for more info.
--pkcs12-passwd <pkcs12_passwd>
Password for --pkcs12-der pkcs12 archive. Required on Mac.
-p, --preamble <preamble>...
Prepend copied data with a specified string. Can be specified multiple times.
-P, --preamble-reverse <preamble_reverse>...
Prepend copied data with a specified string (reverse direction). Can be specified multiple times.
--request-header <request_headers>...
[A] Specify HTTP request headers for `http-request:` specifier.
-X, --request-method <request_method> [A] Method to use for `http-request:` specifier
--request-uri <request_uri> [A] URI to use for `http-request:` specifier
--restrict-uri <restrict_uri>
When serving a websocket, only accept the given URI, like `/ws`
This liberates other URIs for things like serving static files or proxying.
-F, --static-file <serve_static_files>...
Serve a named static file for non-websocket connections.
Argument syntax: <URI>:<Content-Type>:<file-path>
Argument example: /index.html:text/html:index.html
Directories are not and will not be supported for security reasons.
Can be specified multiple times. Recommended to specify them at the end or with equal sign like `-F=...`,
otherwise this option may eat positional arguments
--socks5-bind-script <socks5_bind_script>
[A] Execute specified script in `socks5-bind:` mode when remote port number becomes known.
--socks5-destination <socks_destination>
[A] Examples: 1.2.3.4:5678 2600:::80 hostname:5678
--tls-domain <tls_domain>
[A] Specify domain for SNI or certificate verification when using tls-connect: overlay
--udp-multicast <udp_join_multicast_addr>...
[A] Issue IP[V6]_ADD_MEMBERSHIP for specified multicast address. Can be specified multiple times.
--udp-multicast-iface-v4 <udp_join_multicast_iface_v4>...
[A] IPv4 address of multicast network interface. Has to be either not specified or specified the same number
of times as multicast IPv4 addresses. Order matters.
--udp-multicast-iface-v6 <udp_join_multicast_iface_v6>...
[A] Index of network interface for IPv6 multicast. Has to be either not specified or specified the same
number of times as multicast IPv6 addresses. Order matters.
--udp-ttl <udp_ttl> [A] Set IP_TTL, also IP_MULTICAST_TTL if applicable
--protocol <websocket_protocol>
Specify this Sec-WebSocket-Protocol: header when connecting
--server-protocol <websocket_reply_protocol>
Force this Sec-WebSocket-Protocol: header when accepting a connection
--websocket-version <websocket_version> Override the Sec-WebSocket-Version value
--binary-prefix <ws_binary_prefix>
[A] Prepend specified text to each received WebSocket binary message. Also strip this prefix from outgoing
messages, explicitly marking them as binary even if `--text` is specified
--ws-c-uri <ws_c_uri>
[A] URI to use for ws-c: overlay [default: ws://0.0.0.0/]
--ping-interval <ws_ping_interval> Send WebSocket pings each this number of seconds
--ping-timeout <ws_ping_timeout>
Drop WebSocket connection if Pong message not received for this number of seconds
--text-prefix <ws_text_prefix>
[A] Prepend specified text to each received WebSocket text message. Also strip this prefix from outgoing
messages, explicitly marking them as text even if `--binary` is specified
ARGS:
<addr1> In simple mode, WebSocket URL to connect. In advanced mode first address (there are many kinds of
addresses) to use. See --help=types for info about address types. If this is an address for
listening, it will try serving multiple connections.
<addr2> In advanced mode, second address to connect. If this is an address for listening, it will accept only
one connection.
Basic examples:
Command-line websocket client:
websocat ws://ws.vi-server.org/mirror/
WebSocket server
websocat -s 8080
WebSocket-to-TCP proxy:
websocat --binary ws-l:127.0.0.1:8080 tcp:127.0.0.1:5678
Full list of address types:
ws:// Insecure (ws://) WebSocket client. Argument is host and URL.
wss:// Secure (wss://) WebSocket client. Argument is host and URL.
ws-listen: WebSocket server. Argument is host and port to listen.
inetd-ws: WebSocket inetd server. [A]
l-ws-unix: WebSocket UNIX socket-based server. [A]
l-ws-abstract: WebSocket abstract-namespaced UNIX socket server. [A]
ws-lowlevel-client: [A] Low-level HTTP-independent WebSocket client connection without associated HTTP upgrade.
ws-lowlevel-server: [A] Low-level HTTP-independent WebSocket server connection without associated HTTP upgrade.
wss-listen: Listen for secure WebSocket connections on a TCP port
http: [A] Issue HTTP request, receive a 1xx or 2xx reply, then pass
asyncstdio: [A] Set stdin and stdout to nonblocking mode, then use it as a communication counterpart. UNIX-only.
inetd: Like `asyncstdio:`, but intended for inetd(8) usage. [A]
tcp: Connect to specified TCP host and port. Argument is a socket address.
tcp-listen: Listen TCP port on specified address.
ssl-listen: Listen for SSL connections on a TCP port
sh-c: Start specified command line using `sh -c` (even on Windows)
cmd: Start specified command line using `sh -c` or `cmd /C` (depending on platform)
exec: Execute a program directly (without a subshell), providing array of arguments on Unix [A]
readfile: Synchronously read a file. Argument is a file path.
writefile: Synchronously truncate and write a file.
appendfile: Synchronously append a file.
udp: Send and receive packets to specified UDP socket, from random UDP port
udp-listen: Bind an UDP socket to specified host:port, receive packet
open-async: Open file for read and write and use it like a socket. [A]
open-fd: Use specified file descriptor like a socket. [A]
threadedstdio: [A] Stdin/stdout, spawning a thread (threaded version).
- Read input from console, print to console. Uses threaded implementation even on UNIX unless requested by `--async-stdio` CLI option.
unix: Connect to UNIX socket. Argument is filesystem path. [A]
unix-listen: Listen for connections on a specified UNIX socket [A]
unix-dgram: Send packets to one path, receive from the other. [A]
abstract: Connect to UNIX abstract-namespaced socket. Argument is some string used as address. [A]
abstract-listen: Listen for connections on a specified abstract UNIX socket [A]
abstract-dgram: Send packets to one address, receive from the other. [A]
mirror: Simply copy output to input. No arguments needed.
literalreply: Reply with a specified string for each input packet.
clogged: Do nothing. Don't read or write any bytes. Keep connections in "hung" state. [A]
literal: Output a string, discard input.
assert: Check the input. [A]
assert2: Check the input. [A]
seqpacket: Connect to AF_UNIX SOCK_SEQPACKET socket. Argument is a filesystem path. [A]
seqpacket-listen: Listen for connections on a specified AF_UNIX SOCK_SEQPACKET socket [A]
random: Generate random bytes when being read from, discard written bytes.
Full list of overlays:
ws-upgrade: WebSocket upgrader / raw server. Specify your own protocol instead of usual TCP. [A]
http-request: [A] Issue HTTP request, receive a 1xx or 2xx reply, then pass
http-post-sse: [A] Accept HTTP/1 request. Then, if it is GET,
ssl-connect: Overlay to add TLS encryption atop of existing connection [A]
ssl-accept: Accept an TLS connection using arbitrary backing stream. [A]
reuse-raw: Reuse subspecifier for serving multiple clients: unpredictable mode. [A]
broadcast: Reuse this connection for serving multiple clients, sending replies to all clients.
autoreconnect: Re-establish underlying connection on any error or EOF
ws-c: Low-level WebSocket connector. Argument is a some another address. [A]
msg2line: Line filter: Turns messages from packet stream into lines of byte stream. [A]
line2msg: Line filter: turn lines from byte stream into messages as delimited by '\\n' or '\\0' [A]
foreachmsg: Execute something for each incoming message.
log: Log each buffer as it pass though the underlying connector.
jsonrpc: [A] Turns messages like `abc 1,2` into `{"jsonrpc":"2.0","id":412, "method":"abc", "params":[1,2]}`.
timestamp: [A] Prepend timestamp to each incoming message.
socks5-connect: SOCKS5 proxy client (raw) [A]
socks5-bind: SOCKS5 proxy client (raw, bind command) [A]
exit_on_specific_byte: [A] Turn specific byte into a EOF, allowing user to escape interactive Websocat session
What is websocat command equivalent based on nginx site configuration above? I'm sure websocat can do that since it has many options. Or is there another simple websocket server utilities for that?
|
Closest Websocat command line is something like this:
websocat --restrict-uri /vless-ws -bE ws-l:0.0.0.0:8080 --binary-prefix B --text-prefix T ws://127.0.0.1:19002
But there are many imperfections:
Disconnections get detected late
Ping replies get replied by Websocat, not by final endpoint
Message size is limited by Websocat buffer size
X-Real-IP is not filled in
Only /vless-ws would match, not /vless-ws/ or /vless-ws/something.
Why don't just expose 127.0.0.1:19002 directly as port 8080 instead? Are there other things in Nginx config file that are not depicted here?
Note that you can also use Caddy instead of Nginx - it is easy to run it ad-hoc, as non-root, with only a one simple config file, for example:
{
admin off
}
:8080
handle_path /vless-ws/* {
reverse_proxy http://127.0.0.1:19002
}
Obviously, Websocket connections would get forwarded, you don't need to specify those headers manually.
I'm sure websocat can do that since it has many options.
Websocat (at least as of version 1) is not designed for handling different incoming URLs differently, except of some exceptions like --restrict-uri or -F options.
It is expected that user also uses other tools like a web server or plain socat for missing things. Some examples of combining Websocat with other tools are documented in moreexamples.md.
| websocat command argument equivalent for this nginx custom configuration? |
1,398,580,032,000 |
Googling this didn't show up any results. Here's what I mean: I have a binary file named x in my path (not the current folder, but it is in the PATH), and also a folder with the same name in the current working directory. If I type x, I want the binary to execute, but instead it cd's into that folder. How do I fix this?
|
TL; DR
Add this line to your ~/.zshrc:
unsetopt autocd
AUTO_CD Option and howto find it
First of all the option you are looking for is AUTO_CD.
You can easily find it by looking up `man zshoptions`. Use your pagers search function, usually you press / and enter the keyword. With n you jump to the next occurrence. This will bring up the following:
[..]
Changing Directories
AUTO_CD (-J)
If a command is issued that can't be executed as a normal command, and the command is the name of a directory, perform the cd command to that directory.
[..]
The option can be unset using unsetopt AUTO_CD.
Turning it properly off
You are using oh-my-zsh which is described as
"A community-driven framework for managing your zsh configuration"
Includes 120+ optional plugins (rails, git, OSX, hub, capistrano, brew, ant, macports, etc), ...
So the next thing is to find out, how to enable/disable options according to the framework.
The readme.textile file states that the prefered way to enable/disable plugins would be an entry in your .zshrc: plugins=(git osx ruby)
Find out which plugin uses the AUTO_CD option. As discovered from the manpage it can be invoked via the -J switch or AUTO_CD. Since oh-my-zsh is available on github, searching for it will turn up the file lib/theme-and-appearance.zsh.
If you don't want to disable the whole plugin "theme-and-appearance", put a unsetopt AUTO_CD in your .zshrc. Don't modify the files of oh-my-zsh directly, because in case you are updating the framework, your changes will be lost.
Why executables are not invoked directly
Your third question is howto execute a binary directly:
You have to execute your binary file via a path, for example with a prefixed `./` as in `./do-something`. This is some kind of a security feature and should not be changed.
hing of plugging in an USB stick, mounting it and having a look on it with `ls`. If there is a executable called `ls` which deletes your home directory, everything would be gone, since this would have overwritten the order of your $PATH.
If you have commands you call repeatedly, setting up an alias in your .zshrc would be a common solution.
| How to disable "auto cd" in zsh with oh-my-zsh |
1,398,580,032,000 |
I was trying new dev environments including zsh and oh-my-zsh. Now that I have installed oh-my-zsh, it starts by default on my terminals (iTerm2 and terminal) always start with zsh and with the settings on from oh-my-zsh. I was wondering if it was possible to "disable" or stop using zsh and its setup with oh-my-zsh without having to uninstall oh-my-zsh? It would also be nice to know how to turn them back on too.
Currently, my terminals goes into zsh automatically (I think) and use the oh-my-zsh automatically. I want to have more control over that and me able to control both, when the zsh is being used and when the oh-my-zsh features are being used.
One thing I am also interested on knowing is, how do the terminal applications know which shell to start running on start up. That would be nice to be able to control too!
If you explain as much as you can of the "why" of every command you give me, that would useful! :)
I am on OS X. Not sure if that matters, but I tend to like answers more that are more applicable to more general Unix environments rather to my own.
|
The wording of your question is ambiguous, so I can't tell if you mean you want to stop using zsh or you want to stop using oh-my-zsh. I will cover both.
Disabling zsh
Simply run chsh and select whatever shell you were using before. If you don't know what shell you were using before, it is almost certainly bash. This command changes the "login shell" that is associated with your user. Essentially, it changes your default shell.
You will need to open a new terminal window for changes to take effect. If this does not work, you will need to log out and log back in again to reinitialize your environment.
Disabling only oh-my-zsh
Check if ~/.zshrc.pre-oh-my-zsh exists. It probably does. (This file will have been created when the oh-my-zsh installation script moved your previous .zshrc out of the way. .zshrc is a startup file of zsh, similar to .bashrc for bash.)
If it does, do mv ~/.zshrc ~/.zshrc.oh-my-zsh. This will put the oh-my-zsh-created .zshrc out of the way, so we can restore the original, by doing mv ~/.zshrc.pre-oh-my-zsh ~/.zshrc.
If it does not exist, open ~/.zshrc in a text editor. Find the line that says source $ZSH/.oh-my-zsh and either comment it out or remove it. This will disable the initialization of oh-my-zsh.
You will need to restart your shell for changes to take effect.
| How do you "disable" oh-my-zsh (and zsh) without uninstalling it? |
1,398,580,032,000 |
I'm using virtualenv, virtualenvwrapper, zsh, oh-my-zsh, terminator, on Crunchbang.
I'm trying to display the name of the current virtualenv like so
workon example
(example)...
I've tried many solutions none seems to work, here's my .zshrc file, I know it's no big deal to fix it but I can't find the right solution. It has been a long time since the last time I used Linux for Django development, I forgot what I used to do.
Right now, I see username@crunchbang, I can't tell which virtualenv I'm using.
|
Shell's prompt
Inside your virtualenv environment is a file, bin/activate. You can edit this file to change your prompt to whatever you want it to look like. Specifically this section of the file:
...
else
PS1="(`basename \"$VIRTUAL_ENV\"`)$PS1"
fi
...
The variable PS1 is a special variable that controls what a shell's prompt will look like. Changing its value will change your virtualenv prompt:
PS1="(this is my prompt) "
Example
Create a sample environment.
$ virtualenv tst-env
When you're using virtualenv you typically source this file.
$ cd $HOME/tst-env
$ source bin/activate
(tst-env)[saml@grinchy tst-env]$
After making the above change to the variable PS1 in the bin/activate file my prompt is now this:
$ source bin/activate
(tst-env)
Here are the official instructions on how to do this.
| How to display the name of the current Virtualenv? |
1,398,580,032,000 |
I want to be able to start zsh with a custom rc file similar to the command: bash --rc-file /path/to/file
If this is not possible, then is it possible to start zsh, run source /path/to/file, then stay in the same zsh session?
Note: The command zsh --rcs /path/to/file does not work, at least not for me...
EDIT: In its entirety I wish to be able to do the following:
ssh to a remote server "example.com", run zsh, source my configuration located at /path/to/file, all in 1 command. This is where I've struggled, especially because I'd rather not write over any configuration files on the remote machine.
|
From the man pages:
STARTUP/SHUTDOWN FILES
Commands are first read from /etc/zshenv; this cannot be overridden. Subsequent be‐
haviour is modified by the RCS and GLOBAL_RCS options; the former affects all startup
files, while the second only affects global startup files (those shown here with an
path starting with a /). If one of the options is unset at any point, any subsequent
startup file(s) of the corresponding type will not be read. It is also possible for
a file in $ZDOTDIR to re-enable GLOBAL_RCS. Both RCS and GLOBAL_RCS are set by
default.
Commands are then read from $ZDOTDIR/.zshenv. If the shell is a login shell, com‐
mands are read from /etc/zprofile and then $ZDOTDIR/.zprofile. Then, if the shell is
interactive, commands are read from /etc/zshrc and then $ZDOTDIR/.zshrc. Finally, if
the shell is a login shell, /etc/zlogin and $ZDOTDIR/.zlogin are read.
When a login shell exits, the files $ZDOTDIR/.zlogout and then /etc/zlogout are read.
This happens with either an explicit exit via the exit or logout commands, or an
implicit exit by reading end-of-file from the terminal. However, if the shell termi‐
nates due to exec'ing another process, the logout files are not read. These are also
affected by the RCS and GLOBAL_RCS options. Note also that the RCS option affects
the saving of history files, i.e. if RCS is unset when the shell exits, no history
file will be saved.
If ZDOTDIR is unset, HOME is used instead. Files listed above as being in /etc may
be in another directory, depending on the installation.
As /etc/zshenv is run for all instances of zsh, it is important that it be kept as
small as possible. In particular, it is a good idea to put code that does not need
to be run for every single shell behind a test of the form `if [[ -o rcs ]]; then
...' so that it will not be executed when zsh is invoked with the `-f' option.
so you should be able to set the environment variable ZDOTDIR to a new directory to get zsh to look for a different set of dotfiles.
As the man page suggests, RCS and GLOBAL_RCS are not paths to rc files, as you are attempting to use them, but rather options you can enable or disable. So, for instance, the flag --rcs will enable the RCS option, causing zsh to read from rc files. You can use the following command-line flags to zsh to enable or disable RCS or GLOBAL_RCS:
--globalrcs
--rcs
-d equivalent to --no-globalrcs
-f equivalent to --no-rcs
To answer your other question:
is it possible to start zsh, run "source /path/to/file", then stay in
the same zsh session?
Yes, this is pretty easy according to the above directions. Just run zsh -d -f and then source /path/to/zshrc.
| Start zsh with a custom zshrc |
1,398,580,032,000 |
I'm using macOS 10.15.2 with iTerm2, zsh 5.7.1 and oh-my-zsh (theme robbyrussell).
I noticed that the prompt print is slightly slow respect to the bash one. For example, if I press enter, cursor initially goes at the beginning of the next line then, after a little while, the shell prompt comes in and the cursor is moved to its natural position. For example, if → ~ is the prompt when I'm in my home folder, and [] is my cursor, when I press enter I see:
0 - Idle status
→ ~ []
1 - Immediately after pressing enter
[]
2 - Back to idle status
→ ~ []
This slowness is particularly evident when I quickly press enter multiple times. In this case, I see some blank lines. This is what I see
→ ~
→ ~
→ ~
→ ~
→ ~
→ ~
→ ~
→ ~
→ ~ []
I come from bash shell and when I use bash, there is not such a slowness. I'm not sure this is an issue of oh-my-zsh or its natural behavior. I'd like to know more about this and, eventually, how to fix it. Thanks.
PS: the problem comes from oh-my-zsh and it persists even if I disable all the plugins.
PPS: I previously posted this question on SO. Thanks to user1934428 for his help and for suggesting me to move this question here.
|
I don't know what oh-my-zsh puts in the prompt by default. Maybe it tries to identify the version control status, that's a very popular prompt component which might be time-consuming.
To see what's going on, turn on command traces with set -x.
→ ~
→ ~ set -x
trace of the commands that are executed to calculate the prompt
→ ~
trace of the commands that are executed to calculate the prompt
→ ~ set +x
+zsh:3> set +x
→ ~
→ ~
If the trace is so long that it scrolls off the screen, redirect it to a file with
exec 2>zsh.err
This directs all error messages to the file, not just the trace. To get traces and errors back on the terminal, run
exec 2>/dev/tty
You can customize the trace format through PS4. This is a format string which can contain prompt escapes. For example, to add precise timing information:
PS4='%D{%s.%9.}+%N:%i> '
| oh-my-zsh's prompt is slow: how to fix this |
1,398,580,032,000 |
The first two chars were repeated while I use Tab to do completion. In the screenshot below, cd is repeated.
I have tried rxvt-unicdoe, xterm, terminator. All these terminal emulators have this issue.
Zsh version 5.0.2, config file on-my-zsh
|
If the characters on your command line are sometimes displayed at an offset, this is often because zsh has computed the wrong width for the prompt. The symptoms are that the display looks fine as long as you're adding characters or moving character by character but becomes garbled (with some characters appearing further right than they should) when you use other commands that move the cursor (Home, completion, etc.) or when the command overlaps a second line.
Zsh needs to know the width of the prompt in order to know where the characters of the command are placed. It assumes that each character occupies one position unless told otherwise.
One possibility is that your prompt contains escape sequences which are not properly delimited. Escape sequences that change the color or other formatting aspects of the text, or that change the window title or other effects, have zero width. They need to be included within a percent-braces construct %{…%}. More generally, an escape sequence like %42{…%} tells zsh to assume that what is inside the braces is 42 characters wide.
So check your prompt settings (PS1, PROMPT, or the variables that they reference) and make sure that all escape sequences (such as \e[…m to change text attributes — note that it may be present via some variable like $fg[red]) are inside %{…%}. Since you're using oh-my-zsh, check both your own settings and the definitions that you're using from oh-my-zsh.
The same issue arises in bash. There zero-width sequences in a prompt need to be enclosed in \[…\].
Another possibility is that your prompt contains non-ASCII characters and that zsh (or any other application) and your terminal have a different idea of how wide they are. This can happen if there is a mismatch between the encoding of your terminal and the encoding that is declared in the shell, and the two encodings result in different widths for certain byte sequences. Typically you might run into this issue when using a non-Unicode terminal but declaring a Unicode locale or vice versa.
Applications rely on environment variables to know the locale; the relevant setting is LC_CTYPE, which is determined from the environment variables LANGUAGE, LC_ALL, LC_CTYPE and LANG (the first of these that is set applies). The command locale | grep LC_CTYPE tells you your current setting. Usually the best way to avoid locale issues is to let the terminal emulator set LC_CTYPE, since it knows what encoding it expects; but if that's not working for you, make sure to set LC_CTYPE.
The same symptoms can occur when the previous command displayed some output that didn't end in a newline, so that the prompt is displayed in the middle of the line but the shell doesn't realize that. In this case that would only happen after running such a command, not persistently.
If a line isn't displayed properly, the command redisplay or clear-screen (bound to Ctrl+L by default) will fix it.
| First characters of the command repeated in the display when completing |
1,398,580,032,000 |
I installed oh-my-zsh to make terminal use a bit easier. One thing that bugs me though is the prolific aliases added by it, like "ga", "gap", "gcmsg", "_", which are harder to remember than the original command, and pollutes the command hash table.
So is there a way to disable aliases altogether? Or a way to clear all aliases so that I can put it in my .zshrc?
|
If you don't want any of oh-my-zsh's aliases, but you want to keep other aliases, you can save the aliases before loading oh-my-zsh
save_aliases=$(alias -L)
and restore them afterwards.
eval $save_aliases; unset save_aliases
If you want to remove all aliases at some point, you can use unalias -m '*' (remove all aliases matching *, i.e. all of them).
If you absolutely hate aliases and don't want to ever see one, you can make the alias builtin inoperative: unalias -m '*'; alias () { : }. Or you can simply turn off alias expansion with setopt no_aliases.
| Clear or disable aliases in zsh |
1,398,580,032,000 |
I am having a problem I'm not sure how to get around.
Somehwhere on my system, I have an alias defined as such:
alias subl=\''/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl'\'
I am not sure what file this is in, and I want to change (or actually remove) it.
I could just unalias it in my .zshrc, but that's not as elegant a solution.
When I run alias | grep subl it shows me the alias. Is there a way for me to have it also echo the path to the file defining the alias?
Thanks
|
zsh -x 2>zsh.trace
exit
grep 'alias.*subl' zsh.trace
The -x option causes zsh to print out every command that it executes on stderr. Any command that was executed from reading a file has a prefix with the file name and line. So look for the alias definition in the trace file and you'll know where it was defined.
| how to find file defining an alias |
1,398,580,032,000 |
When I try to login as root, this warning comes up.
luvpreet@DHARI-Inspiron-3542:/$ sudo su
Password:
zsh compinit: insecure directories, run compaudit for list.
Ignore insecure directories and continue [y] or abort compinit [n]?
If I say yes, it simply logs in, and my shell changes from bash to zsh.
If I say no, it says that ncompinit: initialization aborted and logs in.
After login, my shell changes to zsh.
All I ever did related to zsh, was download oh-my-zsh from github.
What is happening and why ?
Using - Ubuntu 16.04 on Dell.
|
You can list those insecure folders by:
compaudit
The root cause of "insecure" is these folders are group writable.
There's a one line solution to fix that:
compaudit | xargs chmod g-w
Please see zsh, Cygwin and Insecure Directories and zsh compinit: insecure directories for reference.
| zsh compinit: insecure directories, run compaudit for list |
1,398,580,032,000 |
I use vi-mode in oh-my-zsh with the af-magic theme.
I want the cursor style to indicate whether I am in normal mode (block) or insert mode (beam), both in zsh and in vim.
This is what I have so far:
In my ~/.zshrc:
# vim mode config
# ---------------
# Activate vim mode.
bindkey -v
# Remove mode switching delay.
KEYTIMEOUT=5
# Change cursor shape for different vi modes.
function zle-keymap-select {
if [[ ${KEYMAP} == vicmd ]] ||
[[ $1 = 'block' ]]; then
echo -ne '\e[1 q'
elif [[ ${KEYMAP} == main ]] ||
[[ ${KEYMAP} == viins ]] ||
[[ ${KEYMAP} = '' ]] ||
[[ $1 = 'beam' ]]; then
echo -ne '\e[5 q'
fi
}
zle -N zle-keymap-select
# Use beam shape cursor on startup.
echo -ne '\e[5 q'
# Use beam shape cursor for each new prompt.
preexec() {
echo -ne '\e[5 q'
}
As found here.
In vim, I use Vundle and terminus.
With these configurations, both zsh and vim work as they should when considered independently.
However, when I enter vim from zsh in insert mode, vim starts in normal mode (as it should) but still shows the beam shape cursor.
Similarly, when I exit vim, I get back to zsh in insert mode, but the cursor is still in block shape (since the last mode in vim was normal).
When after this, I switch modes for the first time (in both zsh and vim), the cursor behaves the way it should again.
How can I make them display the correct cursor after entering and exiting vim as well?
I tried putting
autocmd VimEnter * stopinsert
autocmd VimLeave * startinsert
in my ~.vimrc, but this does not affect the cursor.
|
I think it's better to use precmd() instead of preexec():
# .zshrc
_fix_cursor() {
echo -ne '\e[5 q'
}
precmd_functions+=(_fix_cursor)
This way:
you don't have to change .vimrc
cursor is fixed also when you create a new prompt without executing a command
you don't have to write echo -ne '\e[5 q' twice in your .zshrc.
| Changing cursor style based on mode in both zsh and vim |
1,398,580,032,000 |
In bash, I can use tab-completion to move one directory up and descend down again another path. For example, suppose I'm in $HOME/folder1, and I want to cd to $HOME/folder2. $HOME only has the two child directories folder1 and folder2.
In bash, I could just type
cd ..[TAB]f[TAB]2
and would end up in $HOME/folder2. In my fresh zsh installation, pressing cd ..[TAB] produces a list of those child directories of $HOME/folder1 which have two . in their name.
Is there a simple way to get the behaviour I'm used to? Or is there something even easier to achieve what I want in zsh?
|
Add this to your .zshrc and ..[TAB] will complete to ../ as per bash.
zstyle ':completion:*' special-dirs true
| Tab completion of "../" in zsh |
1,398,580,032,000 |
Now I'm on the oh-my-zsh, but I'm not sure that it is perfect choice. What is the key difference between grml zsh config (github repo) and oh-my-zsh config? In which case should I prefer grml or oh-my-zsh?
|
I am unable to give a detailed report of their differences but I can at least give a broad overview that may help to answer some basic questions and lead you to places where you can learn more.
oh-my-zsh:
Built-in plugin/theme system
Auto updater for core, plugins, and themes
Default behavior easily overridden or extended
Widely popular (which means an active community)
grml-zsh:
Very well documented
Provides many useful built-in aliases and functions (pdf)
Default behavior overridden or extended with .zshrc.pre and .zshrc.local files
Actively developed but not as popular as oh-my-zsh
Basically, the most apparent differences between the two are oh-my-zsh's plugin/theme system and auto-updater. However, these features can be added to grml-zsh with the use of antigen, which is a plugin manager for zsh inspired by oh-my-zsh.
Antigen allows you to define which plugins and theme you wish to use and then downloads and includes them for you automatically. Ironically, though, most of the plugins and themes are pulled from oh-my-zsh's library which means in order for them to work antigen must first load the oh-my-zsh core. So, that approach leads to more or less recreating oh-my-zsh in a roundabout way. However, if you prefer grml's configuration to oh-my-zsh's then this is a valid option.
Bottom line, I believe you just need to try both and see which one works best for you. You can switch back and forth by creating the following files: oh-my-zsh.zshrc (default file installed by oh-my-zsh), grml.zshrc (default grml zshrc), .zshrc.pre, and .zshrc.local.
Then if you want to use oh-my-zsh:
$ ln -s ~/oh-my-zsh.zshrc ~/.zshrc
Or, if you want to use grml:
$ ln -s ~/grml.zshrc ~/.zshrc
If you don't want to duplicate your customizations (i.e. adding files to the custom directory for oh-my-zsh and modifying the pre and local files for grml), one option is to add your customizations to .zshrc.pre and .zshrc.local and then source them at the bottom of your oh-my-zsh.zshrc file like so:
source $HOME/.zshrc.pre
source $HOME/.zshrc.local
Also, if you decide to use antigen you can add it to your .zshrc.local file and then throw a conditional around it to make sure that oh-my-zsh doesn't run it, like so:
# if not using oh-my-zsh, then load plugins with antigen
# <https://github.com/zsh-users/antigen.git>
if [[ -z $ZSH ]]; then
source $HOME/.dotfiles/zsh/antigen/antigen.zsh
antigen-lib
antigen-bundle vi-mode
antigen-bundle zsh-users/zsh-syntax-highlighting
antigen-bundle zsh-users/zsh-history-substring-search
antigen-theme blinks
antigen-apply
fi
| What is the key difference between grml zsh config and oh-my-zsh config |
1,398,580,032,000 |
I am happily using zsh since a while now, and I am quite satisfied with my history settings, which are:
# Write to history immediately
setopt inc_append_history
# History shared among terminals
setopt share_history
# Save extended info in history
setopt extended_history
# Ignore duplicates
setopt hist_ignoredups
But it happens often that I need to use specific commands inside some specific directories. For example, when I am in ~/my_project I usually invoke make target1 && ./run1, but when I am in ~/second_project I usually need make target2 && cat foobar | ./run2.
That is: different directories, but similar commands.
So, I usually cd ~/my_project and type make and then search backward in the history until I find what I need. But if it happen that I worked in second_project, when searching the history I will find some commands that I do not need.
So, my question: does a plugin/setting/something exist for zsh such that, when searching in history, commands invoked in the current directory are displayed first?
Ideally, every other matching history command will appear after those, optionally specifying a max number of priority elements.
I would try to write something like this by myself, but I still do not know how to write custom zsh plugins, how to handle history and so on.
|
There is a plugin that claims to do exactly what you are looking for, appropriately named per directory history plugin:
https://github.com/jimhester/oh-my-zsh/commit/baa187e4b903f39422a84b580e6e617ec3738e09
"Per-directory-history - tracks previous command history both per current directory and globally, with the ability to switch between them on the fly, bound to ctrl-g." says their wiki.
I did not test it myself (yet), but according to the comments it should work.
| Per-directory history in zsh |
1,398,580,032,000 |
I have zsh and oh-my-zsh with default values and can't figure out how to turn off autocorrection for specific commands, that I often use, such as: sudo mc or sudo gem update. The thing is that I have .mc directory and .gem directory and zsh proposes autocorrections (zsh: correct 'mc' to '.mc' [nyae]).
Generally I would like to config zsh so that sudo [smth] is not considered a separate command (which it is not) for autocorrection. What would be a fix for that?
|
Add this to your ~/.zshrc
alias sudo='nocorrect sudo'
| How to disable autocorrection for sudo [command] in zsh? |
1,398,580,032,000 |
I'm using Mac, and I'm trying to time the command execution.
If I do
time echo
it doesn't have any output
But If I do
time ls
it does give me the output of time function
Any idea why that happens?
Update: turns out it's cuz I'm using zsh, with oh-my-zsh installed. It works well in bash, but no output in zsh. Any idea why?
|
In zsh, the time keyword has no effect on builtins (or other similar shell-internal constructs). From this mailing list post:
Additional note: The time builtin applied to any construct that is
executed in the current shell, is silently ignored. So although it's
syntactically OK to put an opening curly or a repeat-loop or the like
immediately after the time keyword, you'll get no timing statistics.
You have to use parens instead, to force a subshell, which is then
timed.
$ time echo
$ time (echo)
( echo; ) 0.00s user 0.00s system 51% cpu 0.001 total
| `time echo` got no output |
1,398,580,032,000 |
I've installed Oh My Zsh with a few custom plugins, such as zsh-autosuggestions. Now while Oh My Zsh supports automatic updates, this doesn't apply to custom plugins (installed to the custom/ subdirectory). How can I make Oh My Zsh update those as well?
|
Oh My Zsh upgrades are handled by the $ZSH/tools/upgrade.sh script. To update any custom plugins (assuming those are Git clones), you can add these lines to the end of the script before the exit command:
printf "\n${BLUE}%s${RESET}\n" "Updating custom plugins"
cd custom/plugins
for plugin in */; do
if [ -d "$plugin/.git" ]; then
printf "${YELLOW}%s${RESET}\n" "${plugin%/}"
git -C "$plugin" pull
fi
done
Now, whenever Oh My Zsh is updated, your custom plugins will be updated too.
| How to auto-update custom plugins in Oh My Zsh? |
1,398,580,032,000 |
I set my $HISTFILE env var to something custom, and my zsh is indeed writing to the new histfile.
But when using up-arrow or other history-searching capabilities, it still reads from ~/.zsh_history.
Ie if I open a new shell, and press up-arrow directly, I will get the last line written to ~/.zsh_history :(
I use oh-my-zsh (with osx brew celery gem git-flow npm pip screen vi-mode last-working-dir docker), and here are the setopts that I use:
# zsh options
#Initial
setopt appendhistory autocd beep extendedglob nomatch notify
#history
HISTSIZE=100000000
SAVEHIST=100000000
setopt HIST_IGNORE_SPACE
setopt extended_history
setopt hist_expire_dups_first
setopt hist_ignore_dups # ignore duplication command history list
setopt hist_ignore_space
setopt hist_verify
setopt inc_append_history
setopt share_history # share command history data
#dirs
setopt autopushd pushdminus pushdsilent pushdtohome pushdignoredups
setopt auto_name_dirs
#appearance
setopt multios
setopt cdablevarS
setopt prompt_subst
#misc
setopt long_list_jobs
#correction
setopt correct_all
#completion
setopt auto_menu # show completion menu on succesive tab press
setopt complete_in_word
setopt completealiases
setopt always_to_end
#syml
setopt chaselinks
#stop pissing me off when using ! in line
unsetopt banghist
# The following lines were added by compinstall
zstyle :compinstall filename '/Users/alex/.zshrc'
# Already in ohmyzsh
#autoload -Uz compinit
#compinit
# End of lines added by compinstall
########
# Key bindings, vi, etc.
autoload -U edit-command-line
zle -N edit-command-line
bindkey -M vicmd 'v' edit-command-line
# create a zkbd compatible hash;
# to add other keys to this hash, see: man 5 terminfo
typeset -A key
key[Home]=${terminfo[khome]}
key[BackSpace]=${terminfo[kbs]}
key[End]=${terminfo[kend]}
key[Insert]=${terminfo[kich1]}
key[Delete]=${terminfo[kdch1]}
key[Up]=${terminfo[kcuu1]}
key[Down]=${terminfo[kcud1]}
key[Left]=${terminfo[kcub1]}
key[Right]=${terminfo[kcuf1]}
key[PageUp]=${terminfo[kpp]}
key[PageDown]=${terminfo[knp]}
# setup key accordingly
[[ -n "${key[Home]}" ]] && bindkey "${key[Home]}" beginning-of-line
[[ -n "${key[BackSpace]}" ]] && bindkey "${key[BackSpace]}" backward-delete-char
[[ -n "${key[BackSpace]}" ]] && bindkey -M vicmd "${key[BackSpace]}" backward-delete-char
bindkey '^H' backward-delete-char
bindkey -M vicmd '^H' backward-delete-char
bindkey "^?" backward-delete-char
bindkey -M vicmd "^?" backward-delete-char
[[ -n "${key[End]}" ]] && bindkey "${key[End]}" end-of-line
[[ -n "${key[Insert]}" ]] && bindkey "${key[Insert]}" overwrite-mode
[[ -n "${key[Delete]}" ]] && bindkey "${key[Delete]}" delete-char
[[ -n "${key[Delete]}" ]] && bindkey -M vicmd "${key[Delete]}" delete-char
[[ -n "${key[Left]}" ]] && bindkey "${key[Left]}" backward-char
[[ -n "${key[Right]}" ]] && bindkey "${key[Right]}" forward-char
[[ -n "${key[Up]}" ]] && bindkey "${key[Up]}" history-beginning-search-backward && bindkey -M vicmd "${key[Up]}" history-beginning-search-backward
[[ -n "${key[Down]}" ]] && bindkey "${key[Down]}" history-beginning-search-forward && bindkey -M vicmd "${key[Down]}" history-beginning-search-forward
bindkey -M vicmd 'h' backward-char
bindkey -M vicmd 'l' forward-char
bindkey -M vicmd '^R' redo
bindkey -M vicmd 'u' undo
bindkey -M vicmd 'ga' what-cursor-position
bindkey -M vicmd 'v' edit-command-line
# Finally, make sure the terminal is in application mode, when zle is
# active. Only then are the values from $terminfo valid.
if (( ${+terminfo[smkx]} )) && (( ${+terminfo[rmkx]} )); then
function zle-line-init () {
printf '%s' "${terminfo[smkx]}"
}
function zle-line-finish () {
printf '%s' "${terminfo[rmkx]}"
}
zle -N zle-line-init
zle -N zle-line-finish
fi
|
Setting HISTFILE in your zsh configuration really should change to where the history is written and from where it is read. It is likely that oh-my-zsh sets HISTFILE=~/.zsh_history before you set it, in which case the history has already been read from ~/.zsh_history.
Looking at the oh-my-zsh code, there are two ways to solve this:
set HISTFILE before loading oh-my-zsh. That is, it has to be set in your ~/.zshrc before the line containing
source $ZSH/oh-my-zsh.sh
This would be a simple solution, if you only want to change HISTFILE.
overload the history.zsh module with your own custom version. Oh-my-zsh loads all files matching $ZSH/lib/*.zsh (where $ZSH usually is ~/.oh-my-zsh) at startup, unless in ${ZSH_CUSTOM}/lib/ is a file with the same name (ZSH_CUSTOM usually is $ZSH/custom). The history settings can be found in $ZSH/lib/history.zsh and can therefore replaced by ${ZSH_CUSTOM}/lib/history.zsh.
If you want to change more of the settings found in $ZSH/lib/history.zsh this is probably the way to go. Otherwise you would have to set HISTFILE before loading oh-my-zsh and everything else after.
A way to change HISTFILE (temporarily) later in a shell session is
fc -p /path/to/new_history
This puts the current history on a stack, sets HISTFILE=/path/to/new_history and reads the history from that file (if it exists). Any new commands will then also be written to the new HISTFILE. You can go back to the original history with fc -P.
| zsh HISTFILE - still read from ~/.zsh_history |
1,398,580,032,000 |
Context
zsh shell,
oh-my-zsh framework,
no special zsh's configuration (same problem with or without zsh-completions): see .zshrc at the end.
Trouble
If a directory contains:
a makefile with targets: hello, hello.o and main.o,
say, 3 files foo, bar and baz,
invoking make + ↹ displays as completion:
bar baz foo hello hello.o main.o makefile
instead of only the makefile' s targets.
Question
How can I customize zsh in order it behaves as bash (which displays only the makefile' s targets) in this respect?
Configuration file
Here is my .zshrc:
export ZSH=/home/bitouze/.oh-my-zsh
ZSH_THEME="gnzh"
plugins=(git zsh-completions)
autoload -U compinit && compinit
source $ZSH/oh-my-zsh.sh
export LANG=fr_FR.UTF-8
source $HOME/.aliases
# texdoc completion
compctl -k "(($(grep ^name $(kpsewhich -var-value TEXMFROOT)/tlpkg/texlive.tlpdb | grep -v '\.' | awk '{print $2}' | tr '\n' ' ')))" texdoc
export ANDROID_HOME="/home/bitouze/Android/Sdk"
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools
export JAVA_HOME=/usr/lib/jvm/jre
#THIS MUST BE AT THE END OF THE FILE FOR SDKMAN TO WORK!!!
export SDKMAN_DIR="/home/bitouze/.sdkman"
[[ -s "/home/bitouze/.sdkman/bin/sdkman-init.sh" ]] && source "/home/bitouze/.sdkman/bin/sdkman-init.sh"
|
You can ask zsh to only display targets tag for the make command completion with
zstyle ':completion:*:*:make:*' tag-order 'targets'
Add above code somewhere after the line
autoload -U compinit && compinit
| Prevent completion of files for 'make' command in zsh shell |
1,398,580,032,000 |
How can I configure Bash, Zsh or Tmux to complete the last matching identifier on the screen? Consider this common scenario:
$ git fetch
remote: Counting objects: 16, done.
remote: Compressing objects: 100% (9/9), done.
remote: Total 9 (delta 4), reused 0 (delta 0)
Unpacking objects: 100% (9/9), done.
From /opt/git/thunder
* [new branch] issue540 -> origin/issue547314
e9204cf..4d42c3f v2.1 -> origin/v2.1
How can I get Bash / Zsh/ Tmux to complete issue547 on the CLI easily? When I press Tab after $ git checkout is Git helpfully completes to issue, but I must complete the digits by myself because all the previous digits do in fact match existent Git branches.
In VIM, pressing Ctrl+P for omnicomplete will complete as the previous match, so in this case issue547314 will in fact be completed. How can I get this behaviour in Bash, in Zsh or in Tmux?
I'm currently using Bash 4.2 and Tmux 1.10 on Ubuntu Server (usually 12.04 LTS). I can update to the latest Ubuntu Server LTS (14.04) if needed.
EDIT: I would not mind any solution that uses Bash, Zsh, or Tmux as long as it is not difficult to use. So Tab or Ctrl+P or some other such shortcut would be fine, but not Alt+Meta+Super+Shift+א.
|
I think that feature that OP is looking for is called dabbrev-expand in Emacs world:
Expand the word in the buffer before point as a dynamic abbrev, by
searching in the buffer for words starting with that abbreviation
(v-expand).
xterm also has dabbrev-expand feature but it's a bit less smart than Emacs counterpart but it's very useful to me and one was one of the reasons for which I switched to xterm. Inside xterm window one can use a custom keybinding specified in ~/.Xresources to invoke dabbrev-expand on a given string. For example, I have the following entry in my ~/.Xresources (I use uxterm, an Unicode version of xterm):
UXTerm*VT100.Translations: #override \n\
Meta <Key>/:dabbrev-expand() \n\
Inside xterm window I can use M-/ (ALT + /) to invoke dabbrev-expand. xterm will look for all strings visible on the screen that start with letters I typed. Example:
$ echo a_very_long_string bye by
$ a_v
If I pressed M-/ now xterm would expand a_v to a_very_long_string. Unfortunately, as I said xterm is not so smart and its dabbrev-expand feature will only work on full strings. So, in your case is would be expanded to issue540 and not issue547314 because issue547314 is a part of origin/issue547314 (think about it as \b in regular expressions, it's a bit similar although most regular expressions engines would catch both occurrences of issue strings in \bissue.+\b). But, you can type or and then pres M-/. xterm will first expand or to origin/v2.1, this is not what we want so press M-/ again and xterm will expand it to origin/issue547314. Now, if you use Bash you can do M-b, C-w and C-e to remove origin/ part. To sum up, dabbrev-expand inside xterm is not as good as in Emacs (and Vim I guess) but it's still faster than rewriting long strings by hand and less typo-prone. And in most cases it will expand directly to the desired string without need to remove redundant parts. You just need to get used to it - look at string you want to have at cursor and see if it's not preceded by something else, and if it is type a preceding part and remove it after expansion.
Note that xterm is not compiled with dabbrev-expand feature by default and you have to enable it explicitly. However, version of xterm in Ubuntu repositories is compiled with dabbrev-expand and you can use it right away.
| Completion of words on the screen as in VIM (Bash or Tmux) |
1,398,580,032,000 |
Not a duplicate:
I'm not looking for a way to complete directory names or execute scripts from a fixed directory. The issue I'm trying to solve is to get completion for the current directory without pressing /
I want zsh to tab-complete . to ./ like bash.
With bash I'm used to press .TABTAB to see all files in the current working directory since it first completes to ./ and then shows all content in that directory. Reason for my desire to avoid / at all cost is that / is way harder on my german keyboard than TAB since it's either with 2 fingers with shift or far away on numpad and I'd rather switch back to bash than type a /. What I'd like to achieve, in other words what bash does:
$ . <TAB>
$ ./ <TAB>
foo.sh somedir/
$ ./ <F><TAB>
$ ./foo.sh <ENTER>
Using zsh / oh-my-zsh when I hit .TAB I get . (dot space) which is not useful at all for me.
Using zstyle ':completion:*' special-dirs true with setopt auto_cd (which is oh-my-zsh default) gives me the even less useful option for ../ on top, so I turned that off already. I'm happy with completion of cd.
There is no . on $PATH and it should stay that way. Though I wouldn't mind completion of e.g. f<TAB> to ./foo.sh for example.
How can I teach zsh to complete . to ./ or even better to local directory content right away? Or is there another way to work with local script files in an efficient way that does not involve /?
|
Great challenge!
Try this on the commandline, if it works add it to ~/.zshrc
bindkey '^I' dotcomplete
zle -N dotcomplete
function dotcomplete() {
if [[ $BUFFER =~ ^'\.'$ ]]; then
BUFFER='./'
CURSOR=2
zle list-choices
else
zle expand-or-complete
fi
}
It adds a function which runs every time you press TAB (^I). If the the line you've currently typed only contains a dot (^=beginning of line, '\.' =super-escape the dot, $=end of line), then replace that dot with a ./ then continue with the normal completion.
It doesn't exactly do what you ask, which is to treat the dot as the current directory. But it will save you they keystrokes you want to save.
| zsh tab complete . to ./ |
1,398,580,032,000 |
I am using this configuration on my mac(unix) to customize my shell. I am using zsh instead of bash and there are too many things along with zsh. This .dotfile configuration contains vim, zsh, git, homebrew, nvm, nginx, neovim and there respective themes and configurations. With Oh-my-zsh I can customize so many themes but here zsh is controlling my shell and ~/.zshrc is a symlink created with .dotfiles/zsh/zshrc.symlink file which I am using from Github's .dotfile bundle. I have renamed oh-my-zsh's version of zshrc file to ~/.zshrc.bak. Also, adding theme configuation to zsh's version of ~\zshrc file doesn't work. How, can I change theme with zsh?
zshrc's symlink from ~/.dotfiles
❯ cat ~/.zshrc
# Ruby Motion android tool
export RUBYMOTION_ANDROID_SDK=/Users/abhimanyuaryan/.rubymotion-android/sdk
export RUBYMOTION_ANDROID_NDK=/Users/abhimanyuaryan/.rubymotion-android/ndk
export DOTFILES=$HOME/.dotfiles
export ZSH=$DOTFILES/zsh
# display how long all tasks over 10 seconds take
export REPORTTIME=10
[[ -e ~/.terminfo ]] && export TERMINFO_DIRS=~/.terminfo:/usr/share/terminfo
# define the code directory
# This is where my code exists and where I want the `c` autocomplete to work from exclusively
if [[ -d ~/code ]]; then
export CODE_DIR=~/code
fi
# source all .zsh files inside of the zsh/ directory
for config ($ZSH/**/*.zsh) source $config
if [[ -a ~/.localrc ]]; then
source ~/.localrc
fi
# initialize autocomplete
autoload -U compinit
compinit
for config ($ZSH/**/*completion.sh) source $config
export EDITOR='nvim'
export PATH=/usr/local/bin:$PATH
# add /usr/local/sbin
if [[ -d /usr/local/sbin ]]; then
export PATH=/usr/local/sbin:$PATH
fi
# adding path directory for custom scripts
export PATH=$DOTFILES/bin:$PATH
# check for custom bin directory and add to path
if [[ -d ~/bin ]]; then
export PATH=~/bin:$PATH
fi
[ -z "$TMUX" ] && export TERM=xterm-256color
# install rbenv
if hash rbenv 2>/dev/null; then
eval "$(rbenv init -)"
fi
if [[ -d ~/.rvm ]]; then
PATH=$HOME/.rvm/bin:$PATH # Add RVM to PATH for scripting
source ~/.rvm/scripts/rvm
fi
# alias git to hub
if hash hub 2>/dev/null; then
eval "$(hub alias -s)"
fi
# source nvm
export NVM_DIR=~/.nvm
if hash brew 2>/dev/null; then
source $(brew --prefix nvm)/nvm.sh
source `brew --prefix`/etc/profile.d/z.sh
fi
# Base16 Shell
# if [ -z "$THEME" ]; then
export THEME="base16-eighties"
# fi
if [ -z "$BACKGROUND" ]; then
export BACKGROUND="dark"
fi
BASE16_SHELL="$DOTFILES/.config/base16-shell/$THEME.$BACKGROUND.sh"
# [[ -s $BASE16_SHELL ]] && source $BASE16_SHELL
source $BASE16_SHELL
oh-my-zsh's version of zshrc file which doesn't work.
❯ cat .zshrc.bak
# Path to your oh-my-zsh installation.
export ZSH=/Users/abhimanyuaryan/.oh-my-zsh
ZSH_THEME="robbyrussell"
plugins=(git)
# User configuration
export PATH="/Users/abhimanyuaryan/bin:/usr/local/bin:/Users/abhimanyuaryan/.rbenv/shims:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin"
# export MANPATH="/usr/local/man:$MANPATH"
source $ZSH/oh-my-zsh.sh
Even if I add ZSH_THEME="agnoster" in ~/.zshrc. The theme doesn't change. It's still the same which Nick provided.
I asked him. He said your oh-my-zsh is clashing with my configurations. Create your own. I don't want to create my own because I am fairly new to all this stuff. Once I am good at tmux, vim, and all this stuff I'll create my own. Until then I just want to use this .dotfiles configuration. Please help me to customize my theme with this configuration. Also, Please help me to understand difference b/w zsh and oh-my-zsh.
|
when you're done editing your ~/.zshrc, in a shell prompt run the command source ~/.zshrc.
it will read the config from ~/.zshrc and it will apply it, it's like reload your config.
| How to change theme with zsh |
1,398,580,032,000 |
I am using zsh and oh-my-zsh on Arch Linux. I am not able to make directory using mkdir
edward@ArchLinux ~ $ sudo mkdir -p /samba/raspberry
[sudo] password for edward:
sudo: nocorrect: command not found
I know it has to do something with auto-completion feature of zsh and alias defined but can't figure out.
|
I have this alias alias sudo='sudo 'defined in a file which I sourced at the end of ~/.zshrc file which overwrote alias sudo='nocorrect sudo' which is defined in .oh-my-zsh/lib/correction.zsh
alias sudo='nocorrect sudo' is required by zsh's auto-completion feature to work
More: How to disable autocorrection for sudo [command] in zsh?
But at same time I need alias sudo='sudo ' for aliases of commands following sudo to work
More: Load aliases from .bashrc file while using sudo
Please note alias sudo='sudo ' works for zsh too
So I can either have zsh's auto-completion feature or have aliases (of other commands) while using sudo so I have now disabled zsh's auto-completion feature.
(Hope I am clear and not confusing.)
| sudo: nocorrect: command not found |
1,398,580,032,000 |
I would like to alias my ls command, but there is a previously defined alias for it which I believe gets invoked first before my definition! I am using .zshrc to define my alias, and here is what I did:
alias ls="ls --classify --almost-all --group-directories-first"
And here is the alias command output:
$ alias | grep "ls="
ls='ls --color=tty'
Is there any possible actions to see where that another alias has been defined? Or overwrite it with the new one?
Note: I use ZSH, and I've already searched for it in .profile and other related files I knew might help. If there is any file I need to check, comment please.
|
The alias command overrides a previous alias by the same name. So generally, if you want your aliases to override the ones defined by a zsh framework, put them at the end of your .zshrc. The same goes for other things such as function definitions, variable assignments, key bindings, etc. Generally speaking, the latest definition wins.
An edge case of “latest definition wins” is that it's only the latest definition for the same kind of object. In particular, aliases, functions and external commands are different kinds of objects, and for example defining a function after defining an alias of the same name does not override the alias. You need to call unalias first. (Also note that the syntax foo () { … } when foo is an alias expands the alias — make sure to unalias first, or use the function foo { … } syntax.)
Occasionally a setting can be overridden at runtime through hook functions. For example frameworks to help with version control often change variables and possibly aliases or functions when entering or leaving a version-controlled directory. When this happens, you have to modify the existing hook or run your own hook after the one you don't fully like.
If you can't figure out where an alias is set, run script -c 'zsh -x', then type exit. This creates a file called typescript with a log of all the commands that zsh runs during its initialization. In that file, search for alias ls=. (It could also be something like alias foo=bar ls=whatever.)
| How to overwrite aliases in my shell (Oh My Zsh)? |
1,398,580,032,000 |
I have recently switched from bash to zsh and now when I type
ls *
It does not simply list all files in this directory, but shows a tree of two levels.
Also
rm -rf somepath/*
fails with the output zsh: no matches found:
This used to work just fine with bash. Can anyone help me to get this behaviour back?
I do have oh-my-zsh installed.
|
ls * would have the same effect in bash. No matter what the shell is, what happens is that the shell first expands the wildcards, and then passes the result of the expansion to the command. For example, suppose the current directory contains four entries: two subdirectories dir1 and dir2, and two regular files file1 and file2. Then the shell expands ls * to ls dir1 dir2 file1 file2. The ls command first lists the names of the arguments that are existing non-directories, then lists the contents of each directory in turn.
$ ls
dir1 dir2 file1 file2
$ ls -F
dir1/ dir2/ file1 file2
$ ls *
file1 file2
dir1:
…
dir2:
…
If ls behaved differently in bash, either you've changed the bash configuration to turn off wildcard expansions, which would turn it off everywhere, or you've changed the meaning of the ls command to suppress the listing of directories, probably with an alias. Specifically, having
alias ls='ls -d'
in your ~/.bashrc would have exactly the effect you describe. If that's what you did, you can copy this line to ~/.zshrc and you'll have the same effect.
The fact that rm -rf somepath/* has a different effect in bash and zsh when somepath is an empty directory is a completely different matter.
In bash, if somepath/* doesn't match any files, then bash leaves the wildcard pattern in the command, so rm sees the arguments -rf and somepath/*. rm tries to delete the file called * in the directory somepath, and since there's no such file, this attempt fails. Since you passed the option -f to rm, it doesn't complain about a missing file.
In zsh, by default, if a wildcard doesn't match any files, zsh treats this as an error. You can change the way zsh behaves by turning off the option nomatch:
setopt no_nomatch
I don't recommend this because having the shell tell you when a wildcard doesn't match is usually the preferable behavior on the command line. There's a much better way to tell zsh that in this case, an empty list is ok:
rm -rf somepath/*(N)
N is a glob qualifier that says to expand to an empty list if the wildcard doesn't match any file.
| How to get asterisk '*' in zsh to have same behaviour as bash? |
1,398,580,032,000 |
I've installed zsh and oh-my-zsh on my Mac terminal, then CTRL+U cut everything I input, no matter where the cursor is.
If it's a common case, how can I set the CTRL+U to the original behavior?
|
Execute, or most likely add it in your ~/.zshrc to always have it:
bindkey "^U" backward-kill-line
| Why does CTRL+U clear everything with zsh, not only the text before cursor, as expected |
1,398,580,032,000 |
UPDATE 3 I've worked out that these annoying autocomplete options are actually usernames. I.e. they exist in /etc/passwd I have users such as _kadmin_admin and _kadmin_changepw and many others starting with an underscore. This may be specific to OSX.
Oh-my-zsh is autocompleting with these usernames when it can't find any other matches. I tried adding these usernames to the "Don't complete uninteresting users" list in ~/.oh-my-zsh/lib/completion.zsh, but that didn't work. I'm not sure why?
Is there anyway to stop oh-my-zsh from autocompleting usernames?
I'm getting frustrated by some weird behaviour in either ZSH or oh-my-zsh. I'm not sure which would be causing it.
The autocomplete seems to be searching some weird directories that I don't want it to. They appear to be some SVN directories, that I know nothing about and have no idea why they would be in the path. (I don't even use SVN)
This behaviour only seems to occur if there are no other matches in the current directory - it must then look in some other path that I have no idea about.
Example:
NOTE: There is nothing in my home dir that matches mi
→ ~ cd mi<tab>
→ ~ cd _kadmin
I.e. it turns mi into _kadmin. I have no idea why it is matching that directory.
If I try to actually change into that directory, I get an error anyway (as it is not the full directory name):
→ ~ cd _kadmin
cd:cd:10: no such file or directory: _kadmin
If I keep pressing <tab> then it will match the full directory name:
→ ~ cd mi<tab><tab><tab>
→ ~ cd kadmin_admin
→ ~_svn
→ ~_svn pwd
/var/empty
I have no idea what is going on there. I have no idea what kadmin_admin is. And why when I change into it, why would I now get a directory name of ~_svn, and then if I PWD it shows /var/empty
This is my path:
/Users/asgeo1/.rvm/gems/ruby-1.9.3-p194/bin:/Users/asgeo1/.rvm/gems/ruby-1.9.3-p194@global/bin:/Users/asgeo1/.rvm/rubies/ruby-1.9.3-p194/bin:/Users/asgeo1/.rvm/bin:/usr/local/php54/bin:/Users/asgeo1/Projects/dotfiles/bin:/Applications/Postgres.app/Contents/MacOS/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/X11/bin
Nothing obvious in there that I can see.
Please someone shed some light on this. It's quite frustrating me!
EDIT: Seems someone has had a similar issue before:
Stop tab completion suggesting 'messagebus' There are no answers on there though :(
UPDATE: This is the cd function which oh-my-zsh applies:
→ ~ which cd
cd () {
if [[ "x$*" = "x..." ]]
then
cd ../..
elif [[ "x$*" = "x...." ]]
then
cd ../../..
elif [[ "x$*" = "x....." ]]
then
cd ../../..
elif [[ "x$*" = "x......" ]]
then
cd ../../../..
else
builtin cd "$@"
fi
}
|
_kadmin is probably a completer function for the kadmin tool - not a directory. If you attempt completion on something that zsh can't find as a command, a directory or a valid and known command argument completion, it then starts to offer completion functions as possible expansion candidates. By default, zsh comes with a lot of completers, many of which you may not need - there are bundles for AIX, BSD, Cygwin, various Linux distributions, etc, and they all get read and installed into the shell. If you attempt an expansion on something zsh can't find, it has all those installed completion functions to offer you instead.
You configure zsh not to offer completer functions by putting this in your ~/.zshrc:
zstyle ':completion:*:functions' ignored-patterns '_*'
Reload the file and you should no longer be offered completion functions for tools you don't have installed. Have a look at the zshcompsys manpage for (a lot) more detail.
EDIT in reply to UPDATE 3
If _kadmin is actually a user account, you can configure zsh to not offer it in completions. It seems the approach is to list the user accounts you do want the shell to consider, which limits any names offered only to those listed. The zstyle line is something like this:
zstyle ':completion:*' users asgeo1 root
I think you can list as many users as you like after the users tag. The shell will then only offer those users' home directories as possible completions for the cd function or builtin.
I don't know why adding the username to the ignored-patterns in the completion.zsh file didn't work - did you reload your config after making the change?
| Why is zsh (oh-my-zsh) completing directories that don't exist? |
1,398,580,032,000 |
As the title says most of the question, how can we run windows executables without specifying the explicit .exe suffix at the end.
For example reducing the call like explorer.exe . to explorer ., or notepad.exe file to notepad file, or docker.exe ps to docker ps, etc.
I was wondering is there's native way to do so, or is there a way to handle the command not found error and redirect to a .exe executable if no linux program are available in $Path with the command name.
Edit:
I forgot to add the environment previously, here it is:
Terminal: Windows Terminal
Linux: Ubuntu 20.04 on WSL (Windows Subsystem for Linux)
Shell: zsh
OS: Windows 10 1909
|
Following the idea given by @DavidG. I have made this, hopefully this will make someone's day :)
The following script will create missing directory, symlinks for all the executables in windows if it does not exists:
#!/usr/bin/zsh
mkdir -p $HOME/.windows_binaries
cd $HOME/.windows_binaries
for ext in $( echo ${PATHEXT-".com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh;.msc"} | tr \; ' ' ); do
for command in ${(M)commands:#*$ext}; do
if [ -f $(basename $command $ext) ]; then; else
ln -s $command $(basename $command $ext)
fi
done
done
And then we can append the ~/.windows_binaries folder into the path so if no linux executable found, windows executable will be triggered:
In $HOME/.zshrc file:
export PATH=$PATH:$HOME/.windows_binaries
Explaination of the above script:
#!/usr/bin/zsh - Shebang that will redirect the script to be executed by zsh, because we did used a filter command that is not available in bash by default.
mkdir -p $HOME/.windows_binaries - If the path does not exist, then create it :)
cd $HOME/.windows_binaries - Change cwd to it
for ext in $(...); do - Loop through each of the extension that is considered as script in the windows
for command in ${(M)commands:#*$ext}; do - $commands indexes all the commands that can be used in the current shell, and using zsh filter we filter the command which ends with $ext extension.
if [ -f $(basename $command $ext) ]; then; else - skip if command's symlink without the extension has been created, else continute to create a symlink with ln -s.
Edit:
Thanks to @user414777, for helping in optimizing the script. Now it does it in about 2-3x faster speed (7-9s):
#!/usr/bin/zsh
mkdir -p $HOME/.windows_binaries
cd $HOME/.windows_binaries
all_exts=${${${PATHEXT-".com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh;.msc"}//;/|}//./}
IFS=$'\n'
if [ $ZSH_VERSION ]; then setopt sh_word_split; fi
for command in $(whence -psm "*.($all_exts)"); do
sym_name=${${command##*/}%.*}
if [ -f $sym_name ]; then; else
ln -s $command $sym_name
fi
done
I also got to understand that the shell substitution for regex-replace / changes to string are better than piping it to some command like tr. And that IFS is not directly used to expand the substitution directly in zsh, we have to configure it before hand.
| How to run windows executables from terminal without the explicitly specifying the .exe extension? |
1,398,580,032,000 |
Could someone please give me the name of the default ZSH theme that Kali uses? Also, if you could please provide a link to it.
|
Kali Linux does not use a separate theme file for its zsh customizations. So you cannot download the Kali Linux zsh theme, drop it in themes/, and set ZSH_THEME to its name as you usually can in Oh My Zsh. Instead, the customizations are made to .zshrc directly. You can inspect .zshrc which is included into Kali Linux and choose what customizations you want.
Be careful to keep a backup of your existing ~/.zshrc. I also used zsh -d -f; source /path/to/file as suggested and explained in another answer to test the configurations without replacing the existing configuration file at all.
Here is some further reading:
Kali Linux zsh for macos
| What ZSH theme does Kali use? |
1,398,580,032,000 |
When I try to autocomplete files (with vim as argument 0):
vim ~/.conf <TAB>
It shows:
_arguments:450: _vim_files: function definition file not found
_arguments:450: _vim_files: function definition file not found
_arguments:450: _vim_files: function definition file not found
It was working fine before!
Other commands:
cat ~/.conf <TAB>
give:
cat ~/.config/
Why is zsh failing only at vim?
|
Turns out that removing all ~/.zcompdump files solved it:
rm -r ~/.zcompdump*
| zsh fails at path completition when command is vim |
1,398,580,032,000 |
so I am currently using manjaro linux and I am using urxvt as my terminal which I love so before all this starts switching the terminal is not an option, sorry if I am being rude.
I installed zsh to it as my default shell and added the theme robbyrussell throught oh-my-zsh. At first it was all fine and everything was working but after an update my icons broke. Particulary(if you are fimiliar with the theme) the arrow icon broke and same with all the icons in all the other themes.
This problem occurrs only with urxvt because when I try with some other terminal such as sterminal the theme works.
Some screenshots you can see here
This is how it's supposed to look(screenshoots taken from sterminal)
And this is how it looks(screenshoots taken from rxvt)
I have been asking for help in reddit, github repos such as oh-my-zsh and robbyrussell officiall repo but no one seemed to help me, so I really am hoping you guys will give me a help.
Here are some information about my os and terminal:
URXVT Version 9.22
Operating System : Manjaro i3 4.12.24-1
No Desktop Envoirment
i3wm as window manager
I am using default oh-my-zsh configurations for my zshrc file and default Xreources from manjaro i3 which you can find here. If you need further information just tell me. Any help would be greatly appreciated!
|
First of all, there is a significant difference between the terminals types rxvt and unicode-rxvt (often abbreviated to urxvt). You have indicated that the terminal you are using is "URXVT Version 9.22", so to avoid confusion, please use the correct name which is not rxvt but urxvt.
As Mikel has pointed out, the Xresources file is telling urxvt to use the 9x15 font which is (a) the old style X11 server provided font method and (b) a limited capability bitmap font.
The oh-my-zsh Github README file explains
many themes require installing the Powerline Fonts in order to render properly
So in order to show the correct arrow shape you need to have the terminal using the appropriate font. Perhaps your update which broke the feature was an update which reset the font usage by urxvt?
As you state that sterminal displays the prompt correctly, check which font that is using, then change the .Xresources in your ${HOME} directory to use that font after verifying that it works with the manual test urxvt -font "font_name". (For the newer method of Xft supplied fonts, font_name is preceeded by "xft:" and followed by ":size=12" for font size).
Having checked in my urxvt, it seems quite a number of well known truetype and opentype monospace fonts do not provide the "right arrow" glyph and just show an empty box. However one readily available standard font that does work (and should be installed on your system) is Deja Vu Sans Mono.
So try firing up a urxvt with
urxvt -font "xft:Deja Vu Sans Mono:size=12" &
and see if your prompt is correctly displayed.
Take a look at https://bbs.archlinux.org/viewtopic.php?id=173477 for discussion on modifying font resource specification for urxvt in an Xresources/Xdefaults file.
PS Do not forget that you can use multiple urxvt terminals more efficiently if you first start the urxvtd daemon and then fire up terminals with urxvtc.
ADDENDUM
Thanks for confirming that you are using urxvt and you have DejaVu Sans Mono installed.
Confirm that there is no font substitution happening with the command entered in terminal at the prompt
fc-match "DejaVu Sans Mono"
producing the output
DejaVuSansMono.ttf: "DejaVu Sans Mono" "Book"
The actual font file location and styles available for the font can be verified with
fc-list | grep --color 'DejaVu Sans Mono'
Now assuming that is all okay, you need to check by firing up a urxvt from the command line of a terminal (sorry for not making that absolutely clear above and I had space between Deja and Vu which might have caused a problem)
urxvt -font "xft:DejaVu Sans Mono:size=12" &
that you can cut'n'paste the right-arrow character (from here) "➜" into that urxvt and that it displays correctly which I have checked does work.
I can also confirm that putting the following into an Xresources file
URxvt.font: xft:DejaVu Sans Mono:autohint=true:size=12
URxvt.boldFont: xft:DejaVu Sans Mono:autohint=true:bold:size=12
URxvt.italicFont: xft:DejaVu Sans Mono:autohint=true:italic:size=12
URxvt.boldItalicFont: xft:DejaVu Sans Mono:autohint=true:bold:italic:size=12
and loading into the Xorg server resource database with xrdb -merge Xresource_file_name to be 100% certain those values will be used and then firing up a terminal with just urxvt at the command line results in a terminal in which the font correctly shows the right arrow character. (you should also notice that characteristic of this font, the l characters are curly and that there is a dot in the center of the zero characters).
The font I normally use in urxvt "Luxi Mono" (easier to read, easy on the eyes IMHO) does not display the right arrow correctly even though the "font-manager" program reveals that "Luxi Mono" does have the glyph. Similarly xterm is also broken but a test in lxterminal, mate-terminal, and xfce4-terminal (checked in preferences that font is set to Luxi Mono) all display the right-arrow correctly. So it does appear that something is broken for some fonts in urxvt and xterm (which if I understand correctly share some code origins) just as the others which work similarly share some common code viz libvte.
| Zsh icons broke in urxvt |
1,398,580,032,000 |
I don't want to see colors in the suggestions of zsh tab-completion. They make the reading harder for me. How can I do that?
Here is my .zshrc:
# _
# _______| |__
# |_ / __| _ \
# / /\__ \ | | |
# /___|___/_| |_|
#
# install oh-my-zsh
[ ! -d ~/.oh-my-zsh ] && git clone https://github.com/robbyrussell/oh-my-zsh.git ~/.oh-my-zsh
# install zsh-autosuggestion
autosuggestions="/home/enan/.zsh/zsh-autosuggestions/zsh-autosuggestions.zsh"
[ ! -f "$autosuggestions" ] && git clone https://github.com/zsh-users/zsh-autosuggestions $HOME/.zsh/zsh-autosuggestions
[ -f "$autosuggestions" ] && source "/home/enan/.zsh/zsh-autosuggestions/zsh-autosuggestions.zsh"
# oh-my-zsh config
export ZSH=/home/enan/.oh-my-zsh
ZSH_THEME=""
DISABLE_LS_COLORS="true"
DISABLE_AUTO_TITLE="true"
export UPDATE_ZSH_DAYS=13
source $ZSH/oh-my-zsh.sh
plugins=( git )
bindkey '^P' up-line-or-beginning-search
bindkey '^N' down-line-or-beginning-search
# Personal customization
BASE16_SHELL=$HOME/.config/base16-shell/
[ -n "$PS1" ] && [ -s $BASE16_SHELL/profile_helper.sh ] && eval "$($BASE16_SHELL/profile_helper.sh)"
executables="/home/enan/Executables/bin"
[ -d "$executables" ] && [[ ":$PATH:" != *$executables* ]] && export PATH=$executables:${PATH}
# FZF settings
[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh
export FZF_DEFAULT_OPTS='--height 100% '
alias ls='ls -CF --color=none'
alias ll='ls -AlF'
alias la='ls -AF'
alias refresh='source ~/.zshrc'
alias screenfetch='screenfetch -t'
alias i3lock='sh ~/Git-repos/dotFiles/lock.sh'
alias emacs='emacs -nw'
alias v='nvim'
alias py2=python2
alias py3=python3
alias t='sh ~/Git-repos/dotFiles/tmux.sh'
# zsh prompt with git info
git_branch() {
git branch --no-color 2>/dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ \1/'
}
git_status() {
# + changes are staged and ready to commit
# ! unstaged changes are present
# ? untracked files are present
# $ changes have been stashed
# ↑ local commits need to be pushed to the remote
local state="$(git status --porcelain 2>/dev/null)"
local output='['
[[ -n $(egrep '^[MADRC]' <<<"$state") ]] && output="$output+"
[[ -n $(egrep '^.[MD]' <<<"$state") ]] && output="$output!"
[[ -n $(egrep '^\?\?' <<<"$state") ]] && output="$output?"
[[ -n $(git stash list) ]] && output="$output$"
[[ -n $(git log --branches --not --remotes) ]] && output="$output↑"
[[ -n $output ]] && output="$output]"
echo $output
}
git_prompt() {
# First, get the branch name...
local branch=$(git_branch)
# Empty output? Then we're not in a Git repository, so bypass the rest
# of the function, producing no output
if [[ -n $branch ]]; then
local state=$(git_status)
# Now output the actual code to insert the branch and status
if [ $state = '[]' ]; then
echo -e " $branch"
else
echo -e " $branch %{$fg_bold[red]%}$state"
fi
fi
}
PROMPT='%{$fg[blue]%}[%n@%m] %{$fg[magenta]%}%c%{$fg[yellow]%}$(git_prompt)
%(?:%{$fg[green]%}❯ :%{$fg[red]%}❯ )%{$reset_color%}'
and a screenshot:
Look at the left pane last command cd <tab> of the terminal in the screenshot.
|
With pure zsh:
zstyle ':completion:*' list-colors
Conversely, to use the same colors as the ls command:
eval "$(dircolors)"
zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS}
This should work even with oh-my-zsh, but oh-my-zsh sometimes has its own way of doing things and I haven't tested with oh-my-zsh.
| Remove colors from zsh tab-completion |
1,398,580,032,000 |
This works
Normally, zsh's tab completion works well.
$ touch foo-1-bar foo-2-bar
$ touch f<Tab>
$ touch foo--bar
^ cursor here
Pressing Tab again brings up a menu from which I can select files.
$ touch foo--bar
foo-1-bar foo-2-bar
This doesn't
However, this doesn't seem to work with strings where the beginning and end match. For example:
touch foo-bar foo-foo-bar
touch f<Tab>
touch foo-bar
^ cursor here. <tab> again.
touch foo-bar
^ cursor here.
No menu is brought up, and there is no opportunity to select foo-foo-bar. Is this expected behaviour or a bug? Is there a setting to make a menu appear in the latter scenario?
I'm using oh-my-zsh. I attempted removing all the completion-related lines from ~/.zshrc, but this made no difference.
|
As per the comments, I tried disabling oh-my-zsh, which fixed this problem. I then went through the oh-my-zsh source, selectively disabling modules.
I previously had CASE_SENSITIVE="true", but commenting out this line fixed it for me. Apparently it's a known bug.
To fix it, I could put the following line in ~/.zshrc after sourcing oh-my-zsh.
zstyle ':completion:*' matcher-list 'r:|=*' 'l:|=* r:|=*'
| How can I get zsh's completion working in the middle of the filename? |
1,398,580,032,000 |
I have configured some directories alias via hash -d hashname=/path/to/directory command.
Completion for that aliases works for a long time like this:
% hashn<TAB> # becomes hashname, pressing <ENTER> works like cd /path/to/directory
Some times ago this has stopped to work. Now that aliases are completable only if starts with ~ sign:
% ~hashn<TAB> # only this works
Is there any way to get previous behaviour?
|
You had the options auto_cd and cdable_vars turned on. With auto_cd, if you type a directory as a command name, the cd command is implied. With cdable_vars, if a directory doesn't exist, or a command doesn't exist with auto_cd, then the name is looked up in the directory hash table.
As long as you're using the “new-style” (compinit) completion system, which oh-my-zsh turns on, the name will be offered as a completion when relevant.
| Zsh: hash directory completion |
1,398,580,032,000 |
I am using zsh with oh-my-zsh. Unfortunately, oh-my-zsh does not use file ~/.ssh/config for hostname auto-completion (see Issue #1009, for instance).
This could easily archived by the following code:
[ -r ~/.ssh/config ] && _ssh_config=($(cat ~/.ssh/config | sed -ne 's/Host[=\t ]//p')) || _ssh_config=()
zstyle ':completion:*:hosts' hosts $_ssh_config
However, if I add the above commands to my ~/.zshrc file, all other sources for hostnames (like ~/.ssh/known_hosts), which are defined in file ~/.oh-my-zsh/lib/completion.zsh, are overridden.
How can I append new completion rules for ':completion:*:hosts' in my ~/.zshrc file?
|
I think you need to retrieve the existing items and append yours.
zstyle -s ':completion:*:hosts' hosts _ssh_config
[[ -r ~/.ssh/config ]] && _ssh_config+=($(cat ~/.ssh/config | sed -ne 's/Host[=\t ]//p'))
zstyle ':completion:*:hosts' hosts $_ssh_config
| How to append / extend zshell completions? |
1,398,580,032,000 |
I have the following personalized theme activated with oh-my-zsh (latest version of zsh and oh-my-zsh):
local return_code="%(?..%{$fg[red]%}%? %{$reset_color%})"
local user_host='%{$terminfo[bold]$fg[green]%}%n @ %m%{$reset_color%}'
local current_dir='%{$terminfo[bold]$fg[cyan]%} %~%{$reset_color%}'
local rvm_ruby=''
local git_branch='$(git_prompt_info)%{$reset_color%}'
PROMPT="${user_host} %D{[%a, %b %d %I:%M:%S]} ${current_dir} ${rvm_ruby} ${git_branch}
%B$%b "
RPS1="${return_code}"
ZSH_THEME_GIT_PROMPT_PREFIX="%{$fg[yellow]%}‹"
ZSH_THEME_GIT_PROMPT_SUFFIX="› %{$reset_color%}"
I have noticed that in the prompt, whenever I have an alias to a directory, it displays the name of the alias as my current directory as opposed to the actual path. While this is an interesting feature, I would like to disable that.
I am relatively new to oh-my-zsh, and I am not sure if this is an oh-my-zsh or zsh feature, but how can I disable it?
|
The prompt escape sequence %~ (included in $current_dir) expands to the current directory, taking abbreviations into account. The abbreviations are:
~ for your home directory;
~joe for the home directory of user joe;
~foo for a named directory: the directory aliased to foo with hash -d foo=…;
~[bar] for a dynamic named directory.
You can use %/ instead of %~. This never uses any directory abbreviation.
If you want to be fancier, you can execute your own code to determine how the current directory is displayed. One approach is to use a parameter substitution inside the prompt string. This requires the prompt_subst option to be set, which oh-my-zsh does (otherwise: setopt prompt_subst). The current directory is always available in the parameter PWD. Here's a simple version that only shortens your home directory to ~:
local current_dir='%{$terminfo[bold]$fg[cyan]%} ${${PWD/#%$HOME/~}/#$HOME\//~/}%{$reset_color%}'
${${PWD/#%$HOME/\~}/#$HOME\//\~/} means: if $PWD is exactly the same as $HOME, then set the result to ~, otherwise set the result to $PWD; then, if the current result begins with $HOME/, then replace this prefix by ~/, otherwise leave the result unchanged.
A clearer approach is to maintain a parameter containing a pretty-printed version of the current directory. Update this parameter in the chpwd hook function which is executed on every current directory change. Also initialize that parameter in your .zshrc.
There's only one chpwd function, so don't override oh-my-zsh's. Oh-my-zsh's chpwd calls the function in the array chpwd_functions, so add yours to the array.
function my_update_pretty_PWD {
case $PWD in
$HOME(/*)#) pretty_PWD=\~${PWD#$HOME};;
*) pretty_PWD=$PWD;;
esac
}
chpwd_functions+=(my_update_pretty_PWD)
my_update_pretty_PWD
local current_dir='%{$terminfo[bold]$fg[cyan]%} ${pretty_PWD}%{$reset_color%}'
If you want to abbreviate users' home directories but not named directories, you can clear the home directories in a subshell and use the % parameter expansion flag to perform the automatic abbreviations in the subshell.
function my_update_pretty_PWD {
pretty_PWD=$(hash -rd; print -lr -- ${(%)PWD})
}
Or if you prefer the inline approach:
local current_dir='%{$terminfo[bold]$fg[cyan]%} $(hash -rd; print -lr -- ${(%)PWD})%{$reset_color%}'
| Preventing zsh from using aliases in CWD (prompt) |
1,398,580,032,000 |
zsh has a great feature of autosuggestion (through a plugin) which remembers as one type in the terminal and then helps out during next instance of typing the same command.
I have around 1000 lines of commands stored in a notepad which will be useful for all my projects.
Is there a way that I can manually add all these 1000 lines of commands to zsh autosuggestion feature without typing it for the first time?
|
Make sure you've configured Zsh to keep enough history entries. On the command line, do
echo $HISTSIZE $SAVEHIST
If the numbers reported are well above 1000, then you're fine. If not, add the following to your .zshrc:
HISTSIZE=20000
SAVEHIST=10000
Find out what the location of your history file is, by doing
echo $HISTFILE
In your histfile, look what the beginning of the first line says. In my case, for example (!), it says
: 1584024476:0;cd /usr/local/share/zsh/functions/zkbd
Copy the beginning of the line up to and including the ;. (Do not copy the timestamp above! Copy the one you find in your own histfile.)
Paste this part in front of every command that you have stored in your notepad.
Close your terminal.
Paste in your entire notepad at the top of your histfile.
Reopen your terminal.
Done! If you're using the history strategy of zsh-suggestions, then the lines you copy-pasted should now be automatically offered as suggestions.
| How to manually add the commands to autosuggestion plugin of zsh? |
1,579,159,590,000 |
For example, when I just want to make cfiles without makefile:
$ make a<tab>
a1.c a2.c a3.c ...
but seems that zsh would detect the command then completes nothing when I hit tab.
It works fine on bash that just lists everything.
Is there the ways like bash do?
My OS is macOS mojave with zsh 5.7.1.
|
From the zsh FAQ:
Add this line to your .zshrc
zstyle ':completion:*' completer _complete _ignored _files
This will perform standard bash file completion if zsh completion fails. You may also need to add
autoload -U compinit && compinit
to you .zshrc file after setting the completer configuration.
| Zsh: complete the files in current directory no matter what command is |
1,579,159,590,000 |
I use ZSH with "OH MY ZSH".
In "OH MY ZSH" variable $GREP_OPTIONS exports with multiple value:
$ echo $GREP_OPTIONS
--color=auto --exclude-dir=.cvs --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn
But when I try use grep I am seeing help for grep.
If I set $GREP_OPTIONS with single value is all work good
$ export GREP_OPTIONS='--color=auto'
$ ls -l ~/ | grep .zsh
drwxr-xr-x 11 petr petr 4096 Sep 10 09:23 .oh-my-zsh
drwxr-xr-x 4 petr petr 4096 Sep 24 13:10 .zsh
lrwxrwxrwx 1 petr petr 19 Sep 22 12:24 .zshenv -> /home/petr/.zsh/env
-rw-r--r-- 1 petr petr 5141 Sep 23 10:31 .zshrc
-rw-r--r-- 1 petr petr 17 Sep 24 12:19 .zsh-update
I work in Tmux. But in pure terminal it also occurs.
My ZSH configs on my GitHub.
UPDATE Example.
Set several grep options:
$ export GREP_OPTIONS='--color=auto --exclude-dir=.git'
$ ls -al ~/ | grep zsh
Usage: grep [OPTION]... PATTERN [FILE]...
Search for PATTERN in each FILE or standard input.
PATTERN is, by default, a basic regular expression (BRE).
Example: grep -i 'hello world' menu.h main.c
Regexp selection and interpretation:
-E, --extended-regexp PATTERN is an extended regular expression (ERE)
-F, --fixed-strings PATTERN is a set of newline-separated fixed strings
-G, --basic-regexp PATTERN is a basic regular expression (BRE)
-P, --perl-regexp PATTERN is a Perl regular expression
-e, --regexp=PATTERN use PATTERN for matching
-f, --file=FILE obtain PATTERN from FILE
-i, --ignore-case ignore case distinctions
-w, --word-regexp force PATTERN to match only whole words
-x, --line-regexp force PATTERN to match only whole lines
-z, --null-data a data line ends in 0 byte, not newline
Miscellaneous:
-s, --no-messages suppress error messages
-v, --invert-match select non-matching lines
-V, --version print version information and exit
--help display this help and exit
--mmap deprecated no-op; evokes a warning
Output control:
-m, --max-count=NUM stop after NUM matches
-b, --byte-offset print the byte offset with output lines
-n, --line-number print line number with output lines
--line-buffered flush output on every line
-H, --with-filename print the file name for each match
-h, --no-filename suppress the file name prefix on output
--label=LABEL use LABEL as the standard input file name prefix
-o, --only-matching show only the part of a line matching PATTERN
-q, --quiet, --silent suppress all normal output
--binary-files=TYPE assume that binary files are TYPE;
TYPE is 'binary', 'text', or 'without-match'
-a, --text equivalent to --binary-files=text
-I equivalent to --binary-files=without-match
-d, --directories=ACTION how to handle directories;
ACTION is 'read', 'recurse', or 'skip'
-D, --devices=ACTION how to handle devices, FIFOs and sockets;
ACTION is 'read' or 'skip'
-r, --recursive like --directories=recurse
-R, --dereference-recursive likewise, but follow all symlinks
--include=FILE_PATTERN search only files that match FILE_PATTERN
--exclude=FILE_PATTERN skip files and directories matching FILE_PATTERN
--exclude-from=FILE skip files matching any file pattern from FILE
--exclude-dir=PATTERN directories that match PATTERN will be skipped.
-L, --files-without-match print only names of FILEs containing no match
-l, --files-with-matches print only names of FILEs containing matches
-c, --count print only a count of matching lines per FILE
-T, --initial-tab make tabs line up (if needed)
-Z, --null print 0 byte after FILE name
Context control:
-B, --before-context=NUM print NUM lines of leading context
-A, --after-context=NUM print NUM lines of trailing context
-C, --context=NUM print NUM lines of output context
-NUM same as --context=NUM
--color[=WHEN],
--colour[=WHEN] use markers to highlight the matching strings;
WHEN is 'always', 'never', or 'auto'
-U, --binary do not strip CR characters at EOL (MSDOS/Windows)
-u, --unix-byte-offsets report offsets as if CRs were not there
(MSDOS/Windows)
'egrep' means 'grep -E'. 'fgrep' means 'grep -F'.
Direct invocation as either 'egrep' or 'fgrep' is deprecated.
When FILE is -, read standard input. With no FILE, read . if a command-line
-r is given, - otherwise. If fewer than two FILEs are given, assume -h.
Exit status is 0 if any line is selected, 1 otherwise;
if any error occurs and -q is not given, the exit status is 2.
Report bugs to: [email protected]
GNU Grep home page: <http://www.gnu.org/software/grep/>
General help using GNU software: <http://www.gnu.org/gethelp/>
Set single option:
$ export GREP_OPTIONS='--color=auto'
$ ls -al ~/ | grep zsh
drwxr-xr-x 11 petr petr 4096 Sep 10 09:23 .oh-my-zsh
drwxr-xr-x 4 petr petr 4096 Sep 24 14:25 .zsh
lrwxrwxrwx 1 petr petr 19 Sep 22 12:24 .zshenv -> /home/petr/.zsh/env
-rw-r--r-- 1 petr petr 5141 Sep 23 10:31 .zshrc
-rw-r--r-- 1 petr petr 17 Sep 24 12:19 .zsh-update
UPDATE 2
ZSH version: zsh 5.0.2 (x86_64-pc-linux-gnu)
Grep version: grep (GNU grep) 2.16
If add options in command line then work normal:
$ unset GREP_OPTIONS
$ ls -al ~/ | grep --color=auto --exclude-dir=.git zsh
drwxr-xr-x 11 petr petr 4096 Sep 10 09:23 .oh-my-zsh
drwxr-xr-x 4 petr petr 4096 Sep 24 15:45 .zsh
lrwxrwxrwx 1 petr petr 19 Sep 22 12:24 .zshenv -> /home/petr/.zsh/env
lrwxrwxrwx 1 petr petr 18 Sep 24 15:17 .zshrc -> /home/petr/.zsh/rc
-rw-r--r-- 1 petr petr 17 Sep 24 12:19 .zsh-update
|
You've made grep an alias for grep $GREP_OPTIONS. Don't do that: the GNU grep command itself parses the GREP_OPTIONS environment variable.
If you want to put options to a command in a variable, make that variable an array, and don't export it (you can't export arrays anyway, environment variables have string values only).
LS_OPTIONS=(--color=auto -q)
alias ls='ls $LS_OPTIONS'
If you have a list of options with a string value (for example because it was passed through the environment), you'll need to split it. The downside of this approach compared to using an array is that whitespace will then be option separators, you can't have whitespace in an option. Use $=VAR to split the value of VAR into separate words on whitespace (or more generally on characters in IFS), like other shells do (zsh won't expand wildcards with $=VAR, use $~VAR to expand wildcards and $=~VAR to do both).
P.S. GREP_OPTIONS is dangerous because it applies in scripts that may be relying on the exact set of options that they pass to grep. --color=auto is about the only safe thing you can put there; it's even officially deprecated since grep 2.21. It would be better to make grep itself an alias (and also egrep and fgrep if you use them):
my_grep_options=(--color=auto --exclude-dir=.cvs --exclude-dir=.git --exclude-dir=.hg --exclude-dir=.svn)
alias grep='grep $my_grep_options' egrep='grep -E $my_grep_options' fgrep='grep -F $my_grep_options'
| Export multiple options in $GREP_OPTIONS |
1,579,159,590,000 |
I am not able to properly display autocompleted filenames that contain accented characters like ã in my shell configuration of zsh and oh-my-zsh.
I've created a filename cão.txt to demonstrate this issue. If you're interested, that means dog in Portuguese.
So, when I try to autocomplete like cat c<tab>, this happens:
% cat ca<0303>o.txt
hi dog
and echo $0 gives me: -zsh
But, if I go to a "plain" zsh session the exact same autocomplete works ok:
% zsh
% echo $0
zsh
% cat cão.txt
hi dog
My locale is like this:
LC_COLLATE="en_US.UTF-8"
LC_CTYPE="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_ALL="en_US.UTF-8"
and the LANG variable I tried it empty, with "en_US.UTF-8" and also "pt_PT.UTF-8". Also, I double-checked the locale settings are exactly the same before and after going to the "plain" zsh session.
Also it works the same way in both the default terminal OSX application and iTerm2.
I'm using zsh version 5.0.7.
Here is my .zshrc file, as well as other dotfiles I'm using.
I've tried uninstalling oh-my-zsh and install it in either the automatic and manual way, always with the same problem of displaying accented characters with autocomplete.
|
This looks like normal default zsh behavior. Whether combining characters are displayed combined during autocompletion is controlled by the combining_chars shell option. To have it complete to cão, put this in your ~/.zshrc file.
setopt combining_chars
I can't reproduce your behavior where this is the default for non-login (zsh vs -zsh) shells.
In the case of zsh -f and the non-login zsh, they are sourcing only /etc/zshenv, and not the other configuration files. Maybe you have your /etc/zshenv configured to setopt combining_chars and something later in the initialization sequence is resetting it.
| Tab autocompletion of accented characters with oh-my-zsh doesn't work |
1,579,159,590,000 |
When I call cd /Users/mu3/apps the prompt simplifies it like this:
mu3 [~/apps]:
Is this possible to do the same for custom path like cd /Users/mu3/Development/Web/test:
mu3 [DEV/test]:
I'm using iTerm + oh-my-zsh.
UPD: I wasn't specific enough and also discovered some new information.
Since I use agnoster theme for zsh shell, it handles a prompt look by itself.
So I ended up with changing this line:
prompt_segment blue black '%~'
to this:
PWDshort="${PWD/#$HOME/~}"
PWDshort="${PWDshort/\~\/_cld\/Dropbox\/Dev\/Web/DEV}"
prompt_segment blue black $PWDshort
Now the problem is that any update apparently breaks this.
Is there any better way to achieve the same result?
|
The standard way to define directory abbreviations for the prompt is to use named directories. Named directories are used when expanding the %~ prompt escape sequence, generalizing ~ to abbreviate your home directory and ~bob to abbreviate Bob's home directory.
mu3 [~]: cd /Users/mu3/Development/Web/test
mu3 [~/Development/Web/test]: hash -d test=$PWD
mu3 [~test]: cd config
mu3 [~test/config]:
The usual way to do this would be to put hash -d test=~/Development/Web/test in your .zshrc. In addition to being used to abbreviate prompts, the named directory can also be used to abbreviate paths, e.g. you can run cd ~test to switch to that directory.
With this method, the abbreviated form always starts with a ~.
| Prompt: replace custom path with a short word like ~ for home |
1,579,159,590,000 |
The find command is not working as expected on my OSX with oh-my-zsh. A few examples:
$ find . -name test
find: .: Invalid argument
$ find
usage: find [-H | -L | -P] [-EXdsx] [-f path] path ... [expression]
find [-H | -L | -P] [-EXdsx] -f path [path ...] [expression]
$ find --version
find: illegal option -- -
usage: find [-H | -L | -P] [-EXdsx] [-f path] path ... [expression]
find [-H | -L | -P] [-EXdsx] -f path [path ...] [expression]
$ find version
find: .: Invalid argument
I'm not sure what's happening here cause the same examples work as expected on my Linux machine. Any ideas on how to debug it?
|
That is because you are trying to use the GNU find, which is default in Linux, but Mac OS X comes with BSD find which has many differences.
To install GNU find you will need Homebrew, pretty easy to install, just follow http://brew.sh/
After that you can install findutils:
brew install findutils
More info and other tools to mimic a Linux environment on your Mac here: https://apple.stackexchange.com/questions/69223/how-to-replace-mac-os-x-utilities-with-gnu-core-utilities
Other option is to read the BSD find man pages and adjust your command. Just run man find, you'll see at the top of the screen "BSD General Commands Manual" confirming that in fact you have BSD find.
| Find not working |
1,579,159,590,000 |
I'm on a system running OS X 10.8.5.
I recently tried to alias ls to ls -G -la command. I opened up ~/.zshrc, put in the alias, relaunched the terminal, but the change didn't take effect. Upon performing which ls, I found out that it's already being aliased to ls -G.
This isn't behaviour I ever set up. Is there any way to find out where this alias is being set?
|
You tagged the question with oh-my-zsh, but did not mention it in the question.
I suspect that oh-my-zsh is creating its own ls alias. If this happens after you define your alias, then it will override yours.
You should probably uncomment DISABLE_LS_COLORS="true" in your .zshrc, or put your alias after the line that does source $ZSH/oh-my-zsh.sh.
| zsh alias being overridden somehow |
1,579,159,590,000 |
I am setting up ZSH with oh-my-zsh, and I want to preserve my .bashrc and .bash_aliases configurations.
From ~/.zshrc I read that:
Aliases can be placed here, though oh-my-zsh users are encouraged to
define aliases within the ZSH_CUSTOM folder.
In the $ZSH_CUSTOM folder I find an example.zsh file that says:
You can put files here to add functionality separated per file, which
will be ignored by git.
Files on the custom/ directory will be automatically loaded by the init
script, in alphabetical order.
Sounds great! Let's copy my bash files in there.
BUT it's not working! If I try one of my aliases I get:
zsh: command not found
I tried removing the dot from the files' names but no change.
What's happening?
(If I source the files manually it works.)
|
Files you create in $ZSH_CUSTOM need to have a file extension of .zsh, according to the documentation:
oh-my-zsh's internals are defined in its lib directory. To change them, just create a file inside the custom directory (its name doesn't matter, as long as it has a .zsh ending)
If you just copied .bashrc and .bash_aliases into it, oh-my-zsh will therefore ignore them.
| Files in $ZSH_CUSTOM not loaded by oh-my-zsh |
1,579,159,590,000 |
I just installed the colored-man-pages zsh plugin.
It works well, but I have an ugly color output on the bottom message:
What is the proper way to personalize the color of the plugins without overwriting everything? It seems the color are set up directly during the plugin activation.
Or maybe it's a bug with my system, fixable with an another way? Indeed, it looks weird to have this default unreadable color output.
I run under Ubuntu 18.10 and gnome-terminal.
|
The format of man pages (groff) doesn't allow colors explicitly, but utilizes a few text decorations like bold or underlines, which in turn can be re-interpreted by a viewer to show colors. And this is exactly what linked plugin is doing, so I suggest to remove this plugin and instead set the colors directly in .zshrc via LESS_TERMCAP variables (I assume you are using less as you man pager and so does this plugin).
Here is the list of variables with description:
export LESS_TERMCAP_mb=$'\e[6m' # begin blinking
export LESS_TERMCAP_md=$'\e[34m' # begin bold
export LESS_TERMCAP_us=$'\e[4;32m' # begin underline
export LESS_TERMCAP_so=$'\e[1;33;41m' # begin standout-mode - info box
export LESS_TERMCAP_me=$'\e[m' # end mode
export LESS_TERMCAP_ue=$'\e[m' # end underline
export LESS_TERMCAP_se=$'\e[m' # end standout-mode
The list of color codes can be found with this script:
#!/bin/bash
echo "PALETTE OF 8 COLORS (bold, high intensity, normal, faint)"
for i in {30..37}; do printf "\e[1;${i}m1;%-2s \e[m" "$i"; done; echo
for i in {90..97}; do printf "\e[${i}m%+4s \e[m" "$i"; done; echo
for i in {30..37}; do printf "\e[${i}m%+4s \e[m" "$i"; done; echo
for i in {30..37}; do printf "\e[2;${i}m2;%-2s \e[m" "$i"; done;
echo -e "\n\n\nPALETTE OF 256 COLORS (only normal)"
j=8
for i in {0..255}; do
[[ $i = 16 ]] && j=6
[[ $i = 232 ]] && j=8
printf "\e[38;5;${i}m38;5;%-4s\e[m" "${i}"
(( i>15 && i<232 )) && printf "\e[52C\e[1;38;5;${i}m1;38;5;%-4s\e[52C\e[m\e[2;38;5;${i}m2;38;5;%-4s\e[m\e[126D" "${i}" "${i}"
[[ $(( $(( $i - 15 )) % $j )) = 0 ]] && echo
[[ $(( $(( $i - 15 )) % $(( $j * 6 )) )) = 0 ]] && echo
done
exit 0
| Personalize colored-man-pages zsh plugin colors |
1,579,159,590,000 |
I'd like to define a function that is called, whenever a shell-user types a command that does not exist. In my case I'd like to log the errors and try alternative commands.
currently, when typing e.g. dgfgsdjagfghsdg the error zsh: command not found: dgfgsdjagfghsdg is shown.
Is there a way to define a function, that get the typed command (+ arguments) as a parameter?
|
Yes.
In the Z shell it is a function named command_not_found_handler.
In the Bourne Again shell it is a function named command_not_found_handle.
Further reading
Intercept "command not found" error in zsh
how to locally redefine 'command_not_found_handle'?
(2x) zsh: command not found
No command 'bla' found, did you mean:?
| How to define a function that handles `command not found`? |
1,579,159,590,000 |
So, I started using zsh and oh-my-zsh recently. I am using the pure (refined) theme and the prompt shows extra info above the prompt.
When I clear the Terminal with Ctrl + L, the whole Terminal gets cleared but the line before the prompt that shows the current directory and git information also get cleared. When I type clear however, the line stays with the prompt while the Terminal gets cleared.
Is there a way to keep that line when I press Ctrl + L? What does that shortcut point to and how can I change it? In my Terminal preferences (I'm on Manjaro Budgie), that key binding is absent in the shortcuts list.
|
Most likely those extra lines are output by precmd, the hook that is run after each command and before the prompt. It is not called automatically upon clear-screen (bound on ^L).
You could redefine clear-screen so it calls it though:
clear-screen() { echoti clear; precmd; zle redisplay; }
zle -N clear-screen
| Keep the whole prompt while clearing zsh terminal with oh-my-zsh |
1,579,159,590,000 |
I trying to install the symfony2 and git plugin for zsh in my docker container.
FROM php:7-fpm
# Install Packages
RUN apt-get update && apt-get install -y vim zsh git
RUN docker-php-ext-install pdo pdo_mysql mysqli zip mbstring
# Instal Oh my Zsh
RUN bash -c "$(curl -fsSL https://raw.github.com/robbyrussell/oh-my-zsh/master/tools/install.sh)"
RUN sed -i -- 's/robbyrussell/wezm+/g' /root/.zshrc # Other awesome theme: random kafeitu sonicradish wezm+
RUN echo "plugins=(git symfony2)" >> ~/.zshrc
But the auto completion does not work. It's like the plugin has not been installed.
Did I miss something?
|
You append plugins=(git symfony2) to your zshrc, which will then look like this:
source $ZSH/oh-my-zsh.sh
plugins=(git symfony2)
For the plugins to get loaded, you need to define the array before including oh-my-zsh.sh, i.e. swap the lines above. Instead of doing echo and append, you can echo to file(or use ADD), concat the original zshrc and move the new file to ~/.zshrc
| Enable a Plugin for Oh my Zsh in Docker |
1,579,159,590,000 |
I recently switched to zsh from bash, and I'm using oh-my-zsh. There's a completion behaviour I don't want: in any directory, the list of autocompletion candidates seems to include the names of all users' home directories.
I wasn't able to find the right zsh option to disable this behaviour out of the hundreds that exist.
|
The option responsible for this behaviour is `cdable_vars'. It's not enabled by default.
See the Manual's chapter about Options for details.
| oh-my-zsh completion on home directory names |
1,579,159,590,000 |
I did the auto-upgrade of oh-my-zsh a few days ago. Now my filtered history (type a few letters and up arrow) no longer works. I did not realize how dependent I became on it.
EDIT:
For example, I used to type a few letters of the command and press up arrow to search my history:
➜ scratch git:(develop) up # press ↑ arrow key
Prompt changes to:
➜ scratch git:(develop) upupdowndownleftrightleftrightbabastartselect # 3 key presses
I don't know how to what version I was running. Currently:
➜ scratch git:(develop) echo $ZSH_VERSION
5.0.2
Here are the lines I have in my .zshrc file that I thought were making the incremental search work:
# Set bindkeys to start search from last word
bindkey '\e[A' history-beginning-search-backward
bindkey '\e[B' history-beginning-search-forward
|
There are two de facto standard escape sequences for cursor keys; different terminals, or even the same terminal in different modes, can send one or the other. For example, xterm sends \eOA for Up in “application cursor mode” and \e[A otherwise. For Down you can encounter both \e[B and \eOB, etc.
One solution is to duplicate your bindings: whenever you bind one escape sequence, bind the other escape sequence to the same command.
bindkey '\eOA' history-beginning-search-backward
bindkey '\e[A' history-beginning-search-backward
bindkey '\eOB' history-beginning-search-forward
bindkey '\e[B' history-beginning-search-forward
Another approach is to always bind one escape sequence, and make the other escape sequence inject the other one.
bindkey '\e[A' history-beginning-search-backward
bindkey '\e[B' history-beginning-search-forward
bindkey -s '\eOA' '\e[A'
bindkey -s '\eOB' '\e[B'
I don't know why upgrading oh-my-zsh would have affected which escape sequence the shell receives from the terminal. Maybe the new version performs some different terminal initialization that enables application cursor mode.
| Broken history search after upgrade of oh-my-zsh |
1,579,159,590,000 |
I am experience some problem in my zsh configuration which is based on oh-my-zsh, which I have described at Physical buffer in terminal is getting misaligned with display in oh-my-zsh configuration.
What I need to know if there is some kind of logging mode in which zsh can produce some information on what is happening in real-time.
The other thing is a print out of the current configuration that a more knowledgeable person can use to track the problem. By configuration I don't mean the just contents of my profile, but some more runtime state related info that can help the diagnosis.
|
You have several options.
First of all, you can setopt xtrace or set -x to get trace info on all calls in the current shell or use zsh -x to start a new shell with that option set. This generates a lot of debug info, though. Plus, it might not even include all the things you are interested in.
If you know more specifically what you are looking for, you can use functions -t <function name> for the specific function that you want to trace.
However, what I find to be the most reliable way to track down problems in any .zshrc config, is to do the following:
cd "$( mktemp -d )"
ZDOTDIR=$PWD HOME=$PWD zsh -df
This creates a temp folder and starts a new subshell without any config files, with its config and home dirs set to the temp folder.
Then you can execute the relevant lines in your .zshrc one by one by pasting them into the sub shell, until you find the point where things start to break.
| Does zsh have some kind of diagnostic mode? |
1,579,159,590,000 |
I tried googling about this but couldn't find any clue: Why does oh-my-zsh pick .zhistory instead of .zsh_history for the value of HISTFILE? Seems like .zsh_history is what more people would expect.
|
Although the ultimate decision comes from the software developer, this seems to be more in line with files zsh uses (from the man page):
$ZDOTDIR/.zshenv
$ZDOTDIR/.zprofile
$ZDOTDIR/.zshrc
$ZDOTDIR/.zlogin
$ZDOTDIR/.zlogout
${TMPPREFIX}* (default is /tmp/zsh*)
/etc/zshenv
/etc/zprofile
/etc/zshrc
/etc/zlogin
/etc/zlogout
Ignoring a leading dot, none of these use a zsh_ prefix, and only a few a full zsh prefix. 3 out of 4 of the dotfiles only have a z and so do 3 of 5 files in /etc.
The choice .zhistory seems to align with the majority here.
| Why does oh-my-zsh pick .zhistory instead of .zsh_history for the value of HISTFILE? |
1,579,159,590,000 |
This is more of a long shot, but here we go:
I use oh-my-zsh with the vcs-plugins git and svn on. I now started on a project where it would be most convenient to use sshfs. The problem that now comes up with that is the following: the git plugin runs git stat after every command, which has a terrible performance in a directory mounted via sshfs. I know that I can determine with df -TP . | grep 'fuse.sshfs' whether I am in a sshfs directory.
I just don't know how/where to turn off the respective plugins. Is there a better way than directly altering the git-prompt.plugin.zsh?
|
A "plugin" in OMZ is just a script. You can't disable part of it without modifying the script.
A workaround would be to use Antigen or Zgen, copy the script to some other location, modify it accordingly, and load it as a separate bundle. Both Antigen and Zgen are designed to support OMZ so you won't have to change anything substantive in your setup.
| Can I conditionally turn certain oh-my-zsh plugins off? |
1,579,159,590,000 |
I've been having an issue with zsh completion that's becoming a rather large annoyance. It's completing options beyond where there is ambiguity. For example, in a directory with these files:
tilertest1x1-00_1408311424.log
tilertest1x1-00_1408311424.root
tilertest2x2-00_1408311501.log
tilertest2x2-00_1408311501.root
tilertest3x3-00_1408311527.log
tilertest3x3-00_1408311527.root
If I type "less ti" and then hit tab, zsh completes to this "tilertest-00_1408311." as opposed to stopping where I want it to ("tilertest"). Strangely, if I provide any kind of path (i.e. "less ./ti") it seems to work just fine. How can I change it to stop at the very first ambiguity? I've included my .zshrc file. I should also note I'm using oh-my-zsh.
# Path to your oh-my-zsh installation.
export ZSH=$HOME/.oh-my-zsh
# Set name of the theme to load.
# Look in ~/.oh-my-zsh/themes/
# Optionally, if you set this to "random", it'll load a random theme each
# time that oh-my-zsh is loaded.
ZSH_THEME="cmilke01"
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"
# Uncomment the following line to use case-sensitive completion.
CASE_SENSITIVE="true"
# Uncomment the following line to disable bi-weekly auto-update checks.
# DISABLE_AUTO_UPDATE="true"
# Uncomment the following line to change how often to auto-update (in days).
# export UPDATE_ZSH_DAYS=13
# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"
# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"
# Uncomment the following line to disable command auto-correction.
DISABLE_CORRECTION="true"
# Uncomment the following line to display red dots whilst waiting for completion.
# COMPLETION_WAITING_DOTS="true"
# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"
# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# HIST_STAMPS="mm/dd/yyyy"
# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder
# Which plugins would you like to load? (plugins can be found in ~/.oh-my- zsh/plugins/*)
# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
plugins=(git)
source $ZSH/oh-my-zsh.sh
# User configuration
export PATH="/usr/local/sbin:/usr/local/bin:/usr/bin:/usr/bin/core_perl"
# export MANPATH="/usr/local/man:$MANPATH"
# You may need to manually set your language environment
# export LANG=en_US.UTF-8
# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
# export EDITOR='vim'
# else
# export EDITOR='mvim'
# fi
# Compilation flags
# export ARCHFLAGS="-arch x86_64"
# ssh
# export SSH_KEY_PATH="~/.ssh/dsa_id"
|
The option that controls a part of this behavior is menu_complete. So, you need:
unsetopt menu_complete
(but it appears that oh-my-zsh already does this). If this isn't sufficient, in case oh-my-zsh does anything special, you may also try:
zstyle ':completion:*' completer _complete
bindkey '\t' expand-or-complete
You can also compare the behavior with zsh -f and in the new shell:
autoload -U compinit
compinit
bindkey -e
If you get the incorrect behavior here, this is probably a bug in your zsh version. Otherwise, try to see which oh-my-zsh change (in its files) triggers the problem. Before hitting the Tab key, you can type CtrlX h in order to get context information on the following completion (this may help you to find what's going on).
Once you have found the solution, to make it permanent, put it in your .zshrc after any change done by oh-my-zsh, so typically at or near the end of the file.
| zshell is tab-completing ambiguous options |
1,579,159,590,000 |
My zsh autocompletion is broken in a strange way. For clean logins everything works but after some time I will get seemingly random autocompletion errors, for different "kinds" of autocompletion. Sometimes ls foo<tab> works but rm foo<tab> won't. I am completely lost on how to debug this.
I could not find a pattern to a particular command causing it. Neither could I see a pattern on what completion works and what doesn't. In my routine I use gnu modules, run make, compilers, nano etc..
The errors I get upon autocompletion look like this:
/bin/zsh:4: _main_complete: function definition file not found
or
(eval):1: _autocd: function definition file not found
(eval):1: _autocd: function definition file not found
(eval):1: _autocd: function definition file not found
_main_complete:173: _ignored: function definition file not found
_main_complete:173: _ignored: function definition file not found
_main_complete:173: _ignored: function definition file not found
or
(eval):1: _rm: function definition file not found
(eval):1: _rm: function definition file not found
(eval):1: _rm: function definition file not found
I have seen similar messages for _sudo and _module.
I am using zsh (5.0.2) with oh-my-zsh in multiple screen sessions on a machine whose home filesystem is on nfs. I attach to the screen sessions automatically on each login with screen -xrR in .zprofile
Two files $HOME/.zcompdump and $HOME/.zompdump-hostname-5.0.2 are created whenever i login. Removing them made no difference.
|
This could be a consequence of running some code that clobbers the variable FPATH or fpath. Check the value of either of these variables; it should be a list of directories where zsh loads functions.
The variables FPATH and fpath are tied (like PATH and path): changing one affects the other. The uppercase FPATH is a string which contains a colon-separated list of directories. The lowercase fpath is an array of directories.
Check your startup scripts for any place where you might use either of these names as variables. Check the list of variable names set or used by zsh (man zshparam) and make sure you don't use any for different purposes.
Completion functions are autoloaded, i.e. loaded the first time they are used. Once you've done any completion in a shell instance, for example, you should no longer see _main_complete: function definition file not found — if _main_complete works but then stops working with this message, something weirder is going on.
| ZSH autocompletion gives seemingly random errors after some time |
1,579,159,590,000 |
I use ZSH with Oh My Zsh and I am trying to define a function called git, as such:
function git() { echo "I'm happy because I am executed!" }
I have placed the function definition in $ZSH/custom/general.zsh.
Everything else in this file works (I have a bunch of aliases there) except this function.
Running which git outputs:
git () {
case $1 in
(commit|blame|add|log|rebase|merge) exec_scmb_expand_args "$_git_cmd" "$@" ;;
(checkout|diff|rm|reset) exec_scmb_expand_args --relative "$_git_cmd" "$@" ;;
(branch) _scmb_git_branch_shortcuts "${@:2}" ;;
(*) "$_git_cmd" "$@" ;;
esac
}
Removing git from plugins=( ... ) didn't work. Trying to find this function in Oh My Zsh yielded no results.
I read the source code of oh-my-zsh.sh, and it seems the custom directory is loaded after all of OMZ's files, so it didn't make any sense to me, that when I placed my function at the bottom of .zshrc it worked.
Any Ideas on how to keep the function in the custom folder? I would like to keep things organized.
|
You probably installed scm_breeze, and my theory is that in your .zshrc the sourcing of scm_breeze.sh is preceeded by oh-my-zsh.sh. And if you put your git function definition at the very end of .zshrc, then you probably exceed the scm_breeze.sh, so that's the reason why it works.
Try to move the line that sources oh-my-zsh.sh to the very end of your .zshrc or at least in a position where it exceeds the sourcing of scm_breeze.sh. Restart zsh and see if it works.
(alternatively you can remove scm_breeze.sh completely)
If it still doesn't work, then back up your .zshrc and all your oh-my-zsh stuffs, then create an empty .zshrc, delete and reinstall oh-my-zsh with curl -L https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh | sh and then put function git() { echo "I'm happy because I am executed!" } in $ZSH/custom/general.zs, I have tested this, it worked for me. After that you can gradually reapply your former settings, step-by-step checking what exactly breaks your configuration.
| Oh-My-Zsh overriding my function? |
1,579,159,590,000 |
I am using zsh and oh-my-zsh on Ubuntu.
To change into the recent directory in the past there was an alias set to - which is the same as cd -. Somehow the alias disappeared at my machine. This might have happened due to updates I pulled from the oh-my-zsh repository.
Now, I would like to add this alias to my own dotfiles. How can I do this?
|
The alias was removed in this commit.
To add it back:
alias -- -='cd -'
Most of POSIX shells need -- for this alias work, only dash doesn't:
$ dash
$ alias -='echo 1'
$ -
1
| How to create hyphen alias for zsh? |
1,579,159,590,000 |
Whenever I create a new window in gnu screen I usually give it a name which persists between disconnects, but I notice that with oh-my-zsh distribution of zsh the title gets reset when I run a command in the window. Basically it gets reset to (x* ~) where x is the window number.
Not only that when I run a command in remote session in that window the title which was set locally gets changed to the command run in the remote window if the remote shell is zsh. This doesn't happen with bash.
e.g. lets say I create a new window in screen with the title as (2* ~) and then set the title to user@remotehost because I am going to connect to remotehost as user. When I run ssh user@remotehost to connect to remotehost the title reverts to (2* ~). When in remotehost I run htop the title changes to htop which I don't want.
It seems as though zsh is propagating the remote windows command into the local window's title even if it is connected to another session. This seems to happen only under zsh as it never happens with bash. Is there some setting zsh or oh-my-zsh that overrides the previous behaviour? I haven't changed by .screenrc on switch to zsh and here it is.
# got a fancy hardstatus line noted below
hardstatus on
hardstatus alwayslastline
# hardstatus string "%w"
# blagged this hardstatus like from https://bbs.archlinux.org/viewtopic.php?id=55618, not quite sure what it does
# extended from http://unix.stackexchange.com/questions/195209 and , uptime command disabled
# http://www.gnu.org/software/screen/manual/html_node/String-Escapes.html#String-Escapes
hardstatus string '%{= kG}%{C}Screen:%{Rk}Host:%H %1`%{c}%{= kG}[%= %{= kw}%?%-Lw%?%{r}(%{W}%n*%f%t%?(%u)%?%{r})%{w}%?%+Lw%?%?%= %{g}][%{C} %d-%m %{W}%c %{g}]'
backtick 1 30 30 sh -c 'screen -ls | grep --color=no -o "$PPID[^[:space:]]*" | cut -d '.' -f 2'
# backtick 2 60 60 /usr/bin/uptime
|
It can be disabled in .zshrc by uncommenting the line:
# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"
It is applied in the functions omz_termsupport_precmd and omz_termsupport_preexec, which are in ~/.oh-my-zsh/lib/termsupport.zsh
| How can I stop zsh (oh-my-zsh) from resetting screen window titles? |
1,579,159,590,000 |
This question is basically a duplicate of this: https://askubuntu.com/questions/91740/how-to-move-all-files-in-current-folder-to-subfolder
But instead I'm asking how to do it in the Mac OS X terminal with oh-my-zsh.
My issue with the solutions given is they don't seem to work in my terminal (replacing the folder "new" in the question with "oldCodeBase" here)
[~/Sid/Moonshine_Machine, 127, master+3]: mv !(oldCodeBase) oldCodeBase
zsh: number expected
What is the number its expecting here?
Moving to the other suggested solution was to use the shopt command.
But I don't seem to have the shopt command available for use:
~/Sid/Moonshine_Machine, 1, master+3]: shopt -s extglob dotglob
zsh: command not found: shopt
So at this point neither solution seems to be working.
EDIT:
I found that "setopt" in zsh appears to be a comparable command to "shopt" but leads to the following issue
[~/Sid/Moonshine_Machine, 127, master+3]: setopt -s extglob dotglob
setopt: no such option: extglob
|
!(pattern) is a ksh glob operator. shopt is a builtin command of the bash shell to enable one of its options (the ones that are not enabled with set -o). bash's extglob option enables a subset of ksh extended glob operators.
In zsh, negation is with the ^ extendedglob operator as @mdmay74 has already shown and zsh has only one set of options all toggled with set -o / set +o (historically setopt / unsetopt). So you'd use:
set -o extendedglob
mv -- ^oldCodeBase(D) oldCodeBase
Note:
-- is needed in case there are file names that start with -
(D) is needed to also move hidden files (in bash, you'd use shopt -s dotglob).
zsh also has a kshglob option to enable ksh's extended globs. But since those are more cumbersome to use than zsh's own extended glob operators, you'd generally only use that as part of the ksh emulation (emulate ksh) used to help interpret scripts written for ksh.
set -o kshglob
mv -- !(oldCodeBase)(D) oldCodeBase
(note that !(oldCodeBase) alone wouldn't work unless you also disabled the bareglobqual option as otherwise (oldCodeBase) would be taken as a glob qualifier).
More generally, you can't assume that one thing that works in one language will work the same in another language, unless that thing is from a standard or common heritage that they both share. bash and zsh both have Bourne, Korn and Csh heritage, each have a mode in which they try to be POSIX compliant and have also copied some features from each other, but their syntax is generally different.
| How to move all files in a folder to a sub folder in zsh w/ Mac OS X? |
1,579,159,590,000 |
I had several Aliases defined on my terminal Zsh (Mac OSx), after installing Oh My Zsh I cannot execute my old aliases, and by running the alias I see a list of many new aliases added by Oh My Zsh. Does this mean it overrode my old ones? Is it possible to recover the old aliases?
|
Unless you installed it in a extremely unconventional way, the aliases that were in ~/.zshrc are now in ~/.zshrc.pre-oh-my-zsh. You can copy them from there.
| Lost my Aliases after installing Oh my Zsh |
1,579,159,590,000 |
Say I have written the following command but haven't yet pressed enter to execute it:
$ ls dir1 dir2 dir3
Is there a way to replace given characters without manually changing them in every location they are? For example, I'd like to press some shortcut, enter string to be replaced (say, dir) and then enter another string as its replacement (say 'directory`).
|
There's a replace-string autoloadable widget for that. Add to your ~/.zshrc:
autoload replace-string
zle -N replace-string
zle -N replace-string-again
bindkey '\eg' replace-string-again
bindkey '\er' replace-string
Then press Alt+r to invoke. Alt+g to repeat the last substitution. See info zsh replace-string for details.
| Replace string in command to be executed in zsh |
1,579,159,590,000 |
I customized the directory and file colors for ls and cd + TAB. Here is my configuration.
My configuration
My system environment.
Ubuntu 10.10
zsh 4.3.10 (x86_64-unknown-linux-gnu)
oh-my-zsh // http://git://github.com/robbyrussell/oh-my-zsh.git
Terminal
My .zshrc in $HOME.
// .zshrc
echo "Sourcing $0."
ZSH=$HOME/.oh-my-zsh
ZSH_THEME="josh"
source $ZSH/oh-my-zsh.sh
A custom zsh script in ~/.oh-my-zsh/custom/completion.zsh
// completion.zsh
echo "Sourcing $0."
# Same completion colors when using cd as with ls.
zstyle ':completion:*:default' list-colors ${(s.:.)LS_COLORS}
zstyle ':completion:*:*:*:*:*' menu yes select
A custom zsh script in ~/.oh-my-zsh/custom/theme-and-appearance.zsh
// theme-and-appearance.zsh
echo "Sourcing $0."
export LS_COLORS='di=1;34:ln=35:so=32:pi=0;33:ex=32:bd=34;46:cd=34;43:su=0;41:sg=0;46:tw=1;34:ow=1;34:'
The problem description.
When I open the Terminal for the first time 3 files are sourced. Notice, that .zshrc does appear but not with its path nor file name.
Sourcing zsh.
Sourcing /home/john/.oh-my-zsh/custom/completion.zsh.
Sourcing /home/john/.oh-my-zsh/custom/theme-and-appearance.zsh.
Using the ls command the directory listing looks as expected. Though, when I use the cd command and TAB for autocompletion directory colors are not the same as with ls.
Then I source the configuration once again. Notice, this time .zshrc does appear with its full path and file name. I am not sure whether this contributes to the problem explained here.
$ . ~/.zshrc
Sourcing /home/john/.zshrc.
Sourcing /home/john/.oh-my-zsh/custom/completion.zsh.
Sourcing /home/john/.oh-my-zsh/custom/theme-and-appearance.zsh.
Now both ls and cd + TAB use the same colors.
Question
How do I have to change my configuration that the customization is loaded as soon as I open the Terminal application?
|
The problem is in the order the files are sourced. LS_COLORS must be defined before you run zstyle ':completion:*:default' list-colors ${(s.:.)LS_COLORS}.
You can fix this by renaming the files to something like 00theme-and-appearance.zsh and 01completion.zsh.
| Terminal does not source .zshrc with custom colors for ls and cd command |
1,579,159,590,000 |
When I use bash in ubuntu and I type aa wrong command, it can guess for me, which correct common I could use:
bash:
haochen@ubuntu-dd:~$ aptget
No command 'aptget' found, did you mean:
Command 'apt-get' from package 'apt' (main)
oh-my-zsh:
# haochen @ ubuntu-dd in ~ [9:13:14] C:100
$ aptget
zsh: command not found: aptget
Is there any settings that can enable this feature?
|
Enable command-not-found plugin from oh-my-zsh
Refer to https://github.com/robbyrussell/oh-my-zsh/wiki/Plugins
| oh-my-zsh can't guess correct command |
1,579,159,590,000 |
I have got used to using tab-autocompleting inside braces without expanding in zsh. This was possible, while I used zsh with a basic grml-config. Since I migrated to oh-my-zsh, I can't reproduce this behaviour.
Example:
$ touch dir/{some_file,other_f<TAB>}
The behaviour I want:
$ touch dir/{some_file,other_file}
The behaviour I get:
$ touch dir/some_file dir/other_f
Instead of autocompleting, a tab expands the braces, defeating the purpose of the brace expansion, whenever I tab for any of the filenames.
I have searched for an answer in the manpages and the zsh-sites for anything relevant, but I couldn't find anything satisfying. Since I am still fresh to zsh, I am not sure, what to look for exactly, though.
I would appreciate any pointers on where to find any explanations relevant to this question.
Thank you in advance for any helpful input!
|
As Thor pointed out in his comment, the autocompletion in braces only works, until you put the closing brace.
So:
touch dir/{some_file,other_f<TAB>(without the closing brace!) autocompletes the filename, so you get touch dir/{some_file,other_file
touch dir/{some_file,other_f<TAB>}(with the closing brace!) expands the braces first, so you get touch dir/some_file dir/other_f
| Change completion behaviour with brace expansion in zsh |
1,579,159,590,000 |
I have zsh set up with Oh-My-Zsh.
The z plugin allows me to jump to recently used directories.
When I type z name<TAB>, it autocompletes name from the list of recently visited dirs by matching name against the list.
Sometimes the result contains only a single entry, when I know there should be multiple. I have debugged the $reply variable and it happens if all entries have the same prefix, e.g. /path/to/dir, containing dirs with name
In this case there is only the prefix in the autocomplete menu instead of full list of matched dirs. Hitting <TAB> again after expansion, triggers a new call to z script complete function now with the full common prefix instead of my search query , e.g. /path/to/dir
When I press <Shift+Tab> which is bound to reverse-menu-complete
zsh properly selects the last item and shows the full list.
Is there a way to make Tab immediately show all completions, without first inserting the common prefix?
|
Add this to your .zshrc file, after sourcing Oh-My-Zsh:
bindkey '\t' menu-complete
Now Tab will behave exactly the same as ShiftTab, but in the opposite direction.
Alternatively, for more control over how completion behaves, install my Zsh Autocomplete plugin.
| How to make `zsh` immediately show all completions, without first inserting the common prefix? |
1,579,159,590,000 |
In my screenshot, the section headers ("recent branches", "local head", etc.) are visually indistinguishable from the completion suggestions.
compinstall doesn't seem to be able to change the styling.
How can I, for example, set the section headers in bold or invert fg/bg colors?
|
See info zsh format (you may need to install a zsh-doc package or equivalent).
You can set the format zstyle for completions:
zstyle ':completion:*' format '%K{blue}%F{yellow}Completing %d:%k%f'
Would show the completion headers as something like Completing recent branches: in yellow over a blue background.
You'll find it in the compinstall menus under:
3. Styles for changing the way completions are displayed and inserted.
[...]
1. Change appearance of completion lists: allows descriptions of
completions to appear and sorting of different types of completions.
[...]
1. Print a message above completion lists describing what is being
completed.
[...]
You can set a string which is displayed on a line above the list of matches
for completions. A `%d' in this string will be replaced by a brief
description of the type of completion. For example, if you set the
string to `Completing %d', and type ^D to show a list of files, the line
`Completing files' will appear above that list. Enter an empty line to
turn this feature off. If you enter something which doesn't include `%d',
then `%d' will be appended. Quotation will be added automatically.
description>
You'll find that compinstall does set the style as zstyle ':completion:*' format. That sets the format for all kinds of completions (files, directories, filters...). You can also set different styles for different categories (see the first argument passed to _description in grep -rw _descriptions $fpath):
zstyle ':completion:*:*director*' format '%F{blue}%BCompleting %d:%b%f'
zstyle ':completion:*:*file*' format '%F{magenta}%BCompleting %d:%b%f'
# fallback:
zstyle ':completion:*:descriptions' format '%BCompleting %d:%b'
Though you'll find those tags (files, directories...) are not always use consistently by all completers.
| How can I style the zsh completion section headers? |
1,453,653,909,000 |
In bash, I can put set -P in my .bashrc, and to use absolute paths. That is, if I change to a directory through a symbolic link, and then use cd .., it takes me to that directory's canonical parent, not the directory containing the symbolic link.
How can I configure zsh to always use absolute paths?
|
From zshoptions(1)
CHASE_LINKS (-w)
Resolve symbolic links to their true values when changing direc-
tory. This also has the effect of CHASE_DOTS, i.e. a `..' path
segment will be treated as referring to the physical parent,
even if the preceding path segment is a symbolic link.
So you would setopt CHASE_LINKS somewhere in your .zshrc. There are also flags to cd that will vary how cd behaves.
If the -s option is specified, cd refuses to change the current
directory if the given pathname contains symlinks. If the -P
option is given or the CHASE_LINKS option is set, symbolic links
are resolved to their true values. If the -L option is given
symbolic links are retained in the directory (and not resolved)
regardless of the state of the CHASE_LINKS option.
| How can I set zsh to use physical paths? |
1,453,653,909,000 |
One point in time, I tried oh my zsh but it causes a lot of issues so I'm back at bash. I'm trying to clean up some files and notice there is a oh my zsh folder. The github instructions tell me to run uninstall oh my zsh but I don't see that script in my folder.
Is it safe to remove .oh-my-zsh folder?
|
.oh-my-zsh isn't used by anything but oh-my-zsh. If you use bash, you can just remove it.
The instructions tell you to run the command uninstall_oh_my_zsh. This is a function that you can invoke from zsh running oh-my-zsh. If you aren't running oh-my-zsh, you can run tools/uninstall.sh, but all it does is:
remove ~/.oh-my-zsh, which you were going to do anyway;
switch your login shell to bash, which you've already done;
restore your old ~/.zshrc, which you didn't have if you never used zsh without oh-my-zsh.
You could also use zsh without oh-my-zsh.
| Is it safe to remove the .oh-my-zsh directory? |
1,453,653,909,000 |
My Oh-my-zsh does the following:
When I run the git log --pretty --oneline command, it shows me a long list of commits, as expected.
As soon as I hit q, it suddenly disappears with the below output:
$ git log --pretty --oneline
FAIL: 141
Why is this happening, and how do I fix it?
|
The number after “FAIL” is the process's exit status. A process's exit status, as reported by the shell, is generally¹:
0 if the program exited normally and reported a success.
1 to 125 if the program exited normally and reported an error.
128+s if the program was killed by signal s, where s is a small integer.
141 means signal 13 which is SIGPIPE. Under the hood, the git command sets up a pipe between two subcommands: one subcommand gathers data and writes data to the pipe, and the other subcommand is the pager less. If you don't view the whole output, the pager exits without waiting for the first subcommand to exit. When the first subcommand next tries to write to the pipe, it is killed by SIGPIPE. This is normal behavior, to avoid having commands continue to calculate and write output that nothing is reading.
There's nothing to fix. But if you find this distracting, you can change your theme to not report a failure status when it's SIGPIPE. The way to do that depends on your oh-my-zsh theme, but from what I can see with a quick look (I don't use oh-my-zsh), the ones that have the word FAIL do it by setting the PROMPT variable, using a prompt expansion conditional to only print the FAIL stuff if the command's exit status is nonzero. So you'd need to change that to also take the “no-failure” branch if the exit status is 141. If you're using a theme bundled with oh-my-zsh, look for FAIL in the theme definition ~/.oh-my-zsh/themes/$ZSH_THEME.zsh-theme. Let's take the example of dst.zsh-theme: the definition is
PROMPT='%(?, ,%{$fg[red]%}FAIL%{$reset_color%}
)
%{$fg[magenta]%}%n%{$reset_color%}@%{$fg[yellow]%}%m%{$reset_color%}: %{$fg_bold[blue]%}%~%{$reset_color%}$(git_prompt_info)
$(prompt_char) '
(Note that it spans multiple lines.) The general pattern is %(?,IFSUCCESS,IFFAILURE) to print IFSUCCESS on success ($? equals 0) and IFFAILURE on failure (including signals). So we'll add another condition if $? equals 141:
PROMPT='%(141?, ,%(?, ,%{$fg[red]%}FAIL%{$reset_color%}
))
%{$fg[magenta]%}%n%{$reset_color%}@%{$fg[yellow]%}%m%{$reset_color%}: %{$fg_bold[blue]%}%~%{$reset_color%}$(git_prompt_info)
$(prompt_char) '
(Note that in addition to prepending %(141?, ,, there's a matching closing parenthesis on the second line.)
¹ The details are off-topic here.
| Oh-my-zsh deletes output of successful command with "FAIL: 141" |
1,453,653,909,000 |
I was wondering whether it is possible to open python files in vim, without typing "vim" in front of it. For example:
Instead of:
vim filename.py
simply
$ filename.py
Would open the file in vim.
I believe it is not upto .vimrc but .bashrc or .zshrc (in my case), which would interpret the .py files to be executable with vim or something. I am using ubuntu (wsl2), with zsh (oh-my-zsh).
It is possible that this has been asked before, but I couldn't find such a question. Thank you.
|
To my personal surprise, yes, there's a way in zsh. This question led me to this answer talking about "suffix aliases" in zsh. Not that yours is a duplicate -- The first question was about a bash way to do it; the other answer was just about "favorite zsh features".
To do it with a suffix alias:
alias -s py=vim
Add that to your ~/.zshrc to make it permanent.
Personally, I'd recommend against it for at least two reasons. First and foremost, as @pizzapants184 pointed out in a comment, this overrides even the ability to execute a Python file using its path. For example, ./run_me.py will not execute, even if it is set as executable, and even if it has a shebang line (e.g. #!/usr/bin/env python3 or #!/usr/bin/python3). It's a neat feature, but it would be nice, IMHO, if it were "smarter."
Also, the extra 3 characters ("vi ") become such muscle memory that will serve you well on other systems that you haven't configured this way or that don't have zsh installed.
Alternative method
And while I still don't necessarily recommend it, you can set the shebang line for an individual file to force it to load in vim when executed:
As the first line of the file (we'll call it edit_me.py):
#!/usr/bin/env vi
Set the file executable:
chmod +x edit_me.py
Running it (e.g. ./edit_me.py) will open it in vim (or fallback to vi if not available).
| Opening py files in vim by default without having to type "vim filename.py" |
1,453,653,909,000 |
If I have the string and copy that with CTRL+SHIFT+C
https://test.invalid/?foo=bar()&baz=$quz{}
And I paste that into the terminal I see the following,
https://test.invalid/\?foo\=bar\(\)\&baz\=$quz\{\}
However, I don't want the ?, (, ), {, }, and = escaped, as I'm using the paste string to fill out curl,
curl "CTRL+SHIFT+C"
How can I disable this character escaping behavior?
|
The problem isn't kitty. If you run /bin/sh and paste you can test that. The problem, in my case, was actually zsh. And specifically oh-my-zsh which has this in the ~/.zshrc conf,
# Uncomment the following line if pasting URLs and other text is messed up.
# DISABLE_MAGIC_FUNCTIONS=true
Uncommenting that fixed my problem.
https://github.com/ohmyzsh/ohmyzsh/issues/5499 original issue, but still broken for me with massively newer stuff.
| How can I disable kitty's paste from escaping? |
1,453,653,909,000 |
Recently installed zsh and oh my zsh but when i open a terminal nothing changes, the bar keeps looking as always but it changes only when i log as root doing sudo su, I have tried almost everyting but nothing changed.
I am using alacritty.
Thanks for your help.
|
Most likely you installed it for root, not your own user.
Read Documentation: Installing OH-MY-ZSH.
Troubleshooting steps:
1. Are your user (not root) using ZSH really? In your user:
% echo $SHELL
/usr/bin/zsh
If not, chsh -s $(which zsh) NO SUDO!
2. Install Oh-My-Zsh without SUDO
sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)
OR
sh -c "$(wget -O- https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
OR
sh -c "$(fetch -o - https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
| Oh my zsh is only working when i log in as root |
1,453,653,909,000 |
I am setting up a zsh shell environment and I wanted to try writing a simple function for my own learning purposes:
# ~/.zsh-extensions/conda_which
# get version in conda env
function conda_which {
# this comes from Flament's answer below
readonly env=${1:?"The environment must be specified."}
readonly pkg=${2:?"The package must be specified."}
conda list -n $env | grep $pkg
}
and in my .zshrc
# ~/.zshrc
# this comes from Terbeck's answer below
fpath=(~/.zsh-extensions/ $fpath)
# this comes from _conda file recommendation for conda autocompletion
fpath+=~/.zsh-extensions/conda-zsh-completion
# this comes from Terbeck's answer below
autoload -U $fpath[1]/*(.:t)
So now I can do:
$ conda_which test_env numpy
numpy 1.23.5 py310h5d7c261_0 conda-forge
instead of
$ conda list -n test_env | grep numpy
because I often forget if it is env list or list env and this is just a toy example.
The issue I am facing is that the output of conda_which losses grep's color highlighting numpy. How do I maintain this?
citations:
@Frank Terbeck's answer on how to autoload custom functions
@Damien Flament's answer on how to pass arguments to zsh functions
|
Grep doesn't have color by default. Instead, the colors can be enabled by the user. Many modern Linux systems ship with grep aliased to grep --color. For example, on my Arch:
$ type grep
grep is aliased to `grep --color'
Now, GNU grep is clever enough to detect when its output is being piped and will disable color unless you use another option that tells it to always print colored output. From man grep:
--color[=WHEN], --colour[=WHEN]
Surround the matched (non-empty) strings, matching lines,
context lines, file names, line numbers, byte offsets, and
separators (for fields and groups of context lines) with escape
sequences to display them in color on the terminal. The colors
are defined by the environment variable GREP_COLORS. WHEN is
never, always, or auto.
The info page for grep gives a bit more detail:
WHEN is ‘always’ to use colors, ‘never’ to not use colors, or ‘auto’ to use colors if standard output is associated with a terminal device and the TERM environment variable’s value suggests that the terminal supports colors. Plain --color is treated like --color=auto; if no --color option is given, the default is --color=never.
What all this means is that if you run grep or grep --color and its output is being piped to something else, then grep won't output color codes. To force it to, you need to use --col9or=always. So, in your function, try something like this:
conda list -n "$env" | grep --color=always "$pkg"
| How to retain color output with custom zsh function? |
1,453,653,909,000 |
everyone!
In my iterm2 (with zsh, oh-my.zsh and powerline2) terminal if I go to certain directories I have a prompt like this:
$ pokemon/electric/pichu/pikachu/raichu
I'd like to have a shorter, but still complete, path representation like this:
$ P/E/P/P/raichu
I have seen this kind of configuration but I haven't been able to set it.
====== EDIT ======
Graphical example:
Can you help with this?
Thanks in advance!
|
We need to edit the .p10k.zsh file
(in my case, I am using powerlevel10k on zsh/oh-my-zsh/iTerm)
nano .p10k.zsh
(or use any other editor of your choice).
We search for the line typeset -g POWERLEVEL9K_SHORTEN_STRATEGY
and add the value as follows:
typeset -g POWERLEVEL9K_SHORTEN_STRATEGY=truncate_from_right
We search for the line typeset -g POWERLEVEL9K_SHORTEN_DELIMITER
and set it empty:
typeset -g POWERLEVEL9K_SHORTEN_DELIMITER=
Finally we search for the line typeset -g POWERLEVEL9K_SHORTEN_DIR_LENGTH
and add the value 1:
typeset -g POWERLEVEL9K_SHORTEN_DIR_LENGTH=1
You should be able to see something like this:
In case you are using a standard zsh theme (without powerlevel10k theme) you can try this:
Add to ~/.zshrc:
setopt prompt_subst
PROMPT='\$ /$(printf "%c/" ${(s./.)PWD:h})${PWD:t} '
(s./.) – splits a path at /.
printf "%c/" – prints the first character of each directory piece.
${PWD:h} – the 'head' of the current directory, i.e. everything but the last element.
${PWD:t} – the 'tail' / last element in the directory path.
extracted from Gairfowl's answer to fish function prompt_pwd but in zsh?
| How to get a shorter Path prompt in powerline10k / zsh? |
1,453,653,909,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,453,653,909,000 |
I'm trying to add auto-completion for some custom ant parameters. However, it seems to be overwriting the existing oh my zsh ant plugin auto-completions which I'd like to keep. Is there a simple way to have both the oh my zsh plugin and my custom ant auto-completion live in harmony?
Here's the existing plugin at ~/.oh-my-zsh/plugins/ant/ant.plugin.zsh
_ant_does_target_list_need_generating () {
[ ! -f .ant_targets ] && return 0;
[ build.xml -nt .ant_targets ] && return 0;
return 1;
}
_ant () {
if [ -f build.xml ]; then
if _ant_does_target_list_need_generating; then
ant -p | awk -F " " 'NR > 5 { print lastTarget }{lastTarget = $1}' > .ant_targets
fi
compadd -- `cat .ant_targets`
fi
}
compdef _ant ant
And my auto complete at ~/my_completions/_ant
#compdef ant
_arguments '-Dprop=-[properties file]:filename:->files' '-Dsrc=-[build directory]:directory:_files -/'
case "$state" in
files)
local -a property_files
property_files=( *.properties )
_multi_parts / property_files
;;
esac
And here is my $fpath, the path for my completion is earlier in the list which I guess is why my script gets precedence.
/Users/myusername/my_completions /Users/myusername/.oh-my-zsh/plugins/git /Users/myusername/.oh-my-zsh/functions /Users/myusername/.oh-my-zsh/completions /usr/local/share/zsh/site-functions /usr/share/zsh/site-functions /usr/share/zsh/5.0.8/functions
|
I think the best way to do it is to extend completion function. Here is how you can do it:
https://unix.stackexchange.com/a/450133
First you would need to find the name of your existing function, to do it, you can bind _complete_help to CTRL-h (or any other shortcut), then type your command and look for completion function. Here is an example running it for git:
% bindkey '^h' _complete_help
% git [press ctrl-h]
tags in context :completion::complete:git::
argument-1 options (_arguments _git)
tags in context :completion::complete:git:argument-1:
aliases main-porcelain-commands user-commands third-party-commands ancillary-manipulator-commands ancillary-interrogator-commands interaction-commands plumbing-manipulator-commands plumbing-interrogator-commands plumbing-sync-commands plumbing-sync-helper-commands plumbing-internal-helper-commands (_git_commands _git)
In this case the completion function is _git.
Next you can redefine it in your .zshrc like this:
# Call the function to make sure that it is loaded.
_git 2>/dev/null
# Save the original function.
functions[_git-orig]=$functions[_git]
# Redefine your completion function referencing the original.
_git() {
_git-orig "$@"
...
}
You wouldn't need to call compdef again, since it is already bound to that function, and you just changed the function definition.
| How to extend existing zsh completion functions? |
1,453,653,909,000 |
I recently switched to oh-my-zsh and I can't get used to the way the arrow up key works. When I enter ssh for example and press up, it only shows me commands starting with ssh while I'd prefer it to show me previous command instead. How could I make it behave the way Bash does, which is what I am already accustomed to?
Note that adding the lines from the answer to the end of my zshrc didn't help and it didn't happen after the upgrade, just after switching to oh-my-zsh from bash.
|
Non-solution
Ironically, the answer in the question that people are proposing as a duplicate … bindkey '\e[A' history-beginning-search-backward
bindkey '\e[B' history-beginning-search-forward … is exactly the wrong answer. It ensures that your terminal's control sequences for the arrow editing keys are mapped by ZLE to the extension widgets history-beginning-search-backward and history-beginning-search-forward that are provided by Oh My ZSH's history-substring-search plug-in.
That is exactly what you do not want.
You're trying to turn this feature off, because you prefer another behaviour; not trying to repair it because it is broken.
Solution
What you want is those keys to map to the widgets as in vanilla Z Shell, Oh My ZSH being a barrelful of extensions to and customizations of the Z Shell that some (but not all) people like. Vanilla Z Shell's widgets have roughly the old Bourne Again shell behaviour that you prefer. (Unlike the Bourne Again shell, though, you if have a multiple-line editing buffer they will move up and down within it before, at the top and bottom edges of the buffer, moving up and down the history.)
Those widgets would be: bindkey "$terminfo[kcuu1]" up-line-or-history
bindkey "$terminfo[kcud1]" down-line-or-history
Note how one works to not hardwire one specific terminal type into one's scripts. One could use "$termcap[ku]" and "$termcap[kd]", alternatively. The Z Shell, presuming that you have the appropriate modules loaded, maintains a map for both. Generally the world prefers terminfo if it has it nowadays, though. To be strictly bulletproof, in something that you use with heterogeneous systems or give to other people, you'll need a test -n in there — just as you'll find the Oh My ZSH extensions doing in fact.
test -n "$terminfo[kcuu1]" && bindkey "$terminfo[kcuu1]" up-line-or-history
test -n "$terminfo[kcud1]" && bindkey "$terminfo[kcud1]" down-line-or-history
(In extremis, to cope with some unlikely possibilities, you'll need some "${terminfo[x]-${termcap[y]}}" variable expansion. The Oh My ZSH extensions do not bother with that latter, and in practice you can likewise largely get away without it. In practice, almost everyone has the termcap and terminfo modules loaded, and all that you have to worry about is whether the record for your current terminal type actually defines the relevant control sequences, which is what the test -n is for.)
A more exact approximation of the Bourne Again shell behaviour would be bindkey "$terminfo[kcuu1]" up-history
bindkey "$terminfo[kcud1]" down-history That's not the vanilla Z Shell default, and after editing your first multiple-line command line you might decide that the default is what you prefer. ☺
| How to make oh-my-zsh history behavior similar to Bash's? |
1,453,653,909,000 |
In bash, when I type screen -x and press tab twice, I get a list of all the running sessions.
In zsh, when I type screen -ls and press tab twice, I get a list of all the running sessions and can tab through them, eventually select one when pressing enter, but this then executes screen -ls session-name when pressing enter again.
What I want in zsh is to get a behavior for -x similar to -ls, so that I don't have to type the session name or select the session and go back and change ls to x.
I can't find the code which implements the screen -ln tab-behavior in order to also implement it for -x, I've been searching/grepping through the list of .oh-my-zsh plugins but am getting nowhere.
Any help is appreciated, or maybe some workflow tips. I use screen a lot and most of it is via screen -x.
|
The code is in _screen (completion is provided natively by zsh, it's not an additional plugin). Zsh completes all sessions for -ls but only attached sessions for -x.
-x is intended to “Attach to a not detached screen session” (per the manual). But it also works if the session is detached. So both behaviors make sense. Ideally, this should be a configuration option for zsh's completion.
To get the behavior you want instead of the current behavior, you need to change the line
'-x[attach to a not detached screen (multi display mode)]: :->attached-sessions' \
to
'-x[attach to a not detached screen (multi display mode)]: :->any-sessions' \
Here's some code you can put in your init file to monkey-patch the completion function to get the behavior you want. It needs to go after compinit (so after the oh-my-zsh lines if you use oh-my-zsh).
# Monkey-patch the screen completion function to complete all sessions
# after -x, not just detached sessions.
autoload +X _screen # load immediately
set -o extendedglob # needed for (#b) and # below and generally a good
# thing to have in interactive shells
functions[_screen]=${functions[_screen]/(#b)(\'-x[^:]#:[^:]#:->)attached-sessions(\')/${match[1]}any-sessions${match[2]}}
| zsh gnu-screen tab completion for `-x` flag similar to `-ls` |
1,453,653,909,000 |
I'm trying to create an alias on ZSH.
The aim of the alias is to activate a python virtualenv.
I've put a line in my .zshrc
alias SOU="source /home/andykw/.zshrc && source $(setopt extendedglob && ls -d .^git/)/bin/activate"
Often I need to change virtual environment with activating a virtual environment in one of the folder, then switching to another folder and activate another virtual environment.
Example: Let's say I'm working with the folder flask_rest and I have to work on another project, django_rest, I will need to deactivate the flask_rest environment and activate the django_rest environment.
Instead of doing it several times with the command line source <folder_name>/bin/activate then go with another folder source <another_folder_name>/bin/activate, I only need to type SOU.
Hope it makes the context clearer.
PS: I'm using Ubuntu with a Windows Subsystem Linux.
|
If all you want is an alias that finds the single ./.*/bin/activate file in the current directory tree and sources it, then all you need is:
alias SOU='source. */bin/activate'
If the glob .*/bin/activate matches multiple files, only the first one will be sourced. Your ~/.zshrc file should be sourced every time you open a new non-login interactive shell session, and you probably don't want to be sourcing it multiple times. I suggest you open a new question to try and understand why you seem to need to source it explicitly.
| create an alias on ZSH but need to type it twice |
1,453,653,909,000 |
I'm trying zsh on Ubuntu 20.04 from Putty. One good feature I like is that zsh automatically show the running command on window title, which is good for forgetful me who forget what is running.
Nonetheless, I would like to append username and hostname to the running command.
As the screenshot shows, what I'm running is htop. Can zsh set title to, say, gqqnbig@tatooine:~ htop, like the title says when I'm not running anything?
I'm also using oh-my-zsh.
Response to Marlon Richert
Yes, I'm using Putty. If I use Bash, as the screenshots show, Putty fails to set the Window title. Please advise.
|
One good feature I like is that zsh automatically show the running command on window title
That's actually Oh-My-Zsh that does that, not Zsh itself.
To get the behavior you want:
From the Oh-My-Zsh file lib/termsupport.zsh, copy the function omz_termsupport_preexec to your .zshrc file
Change the last line (title '$CMD' '%100>...>$LINE%<<') to
title "$ZSH_THEME_TERM_TITLE_IDLE $CMD" \
"%100>...>$ZSH_THEME_TERM_TAB_TITLE_IDLE $LINE%<<"
| How to keep hostname on title when I run commands |
1,453,653,909,000 |
I am having oh-my-zsh installed but the prompt is not showing the proper arrow which I Was expecting . I setup the arch linux from very scratch but I think I am missing those fonts. I am not sure which one is it . Can someone help me how to get this
What I am getting currently is this -
|
The issue of not showing the expected icon is because
You do not have the required fonts ( in this case the '->')
install powerline fonts with your package manager. (debian)
PS: After installation it is required to reset the font cache so that
it can then be reflected in your system.
sudo apt-get install powerline
sudo fc-cache -f -v
else you can also pull the latest code from powerline from this and install manually.
# clone
git clone https://github.com/powerline/fonts.git --depth=1
# install
cd fonts
./install.sh
# clean-up a bit
cd ..
rm -rf fonts
| zsh prompt isn't showing the arrow key due to font issues |
1,453,653,909,000 |
While working on a project, I often have to run these commands sequentially git add --all; git commit -m "some commit message"; git push to push the recent work to the remote repository.
I thought it would be better to write a function, that encapsulates these three commands and put that in my .zshrc file, so it is available everytime I start the shell. So I wrote the following function,
gp() {
git add --all
git commit -m "$*"
git push
}
export -f gp
When I source the .zshrc file or start a new shell session. It throws the following error:
parse error near `()'
I have checked online for the correct syntax for defining function and the above function looks correct to me. I am at loss here on how to resolve this error, will greatly appreciate your help.
|
function-name() command
is one of several function definition syntaxes supported by zsh, the one from the Bourne shell from the early 80s, so that part of your code is fine.
If you get a parse error near `()' error on that, it's likely because from the start the parser is not expecting a function definition.
For instance, that's the error you'd get in:
case x in
gp() {
body
}
As after case x in, zsh expects a case pattern or esac, not a function definition.
So the problem is likely somewhere in a part of the zshrc you're not showing. Syntax errors also often arise when scripts are formatted with MSDOS line ending (CRLF instead of LF) like when they've been edited on a Microsoft Windows systems. dos2unix can be used to fix those.
Other than that note that export -f function-name is a bash-only feature.
zsh has no equivalent to that dangerous feature, though you could implement it by hand by adding some function importing logic in your ~/.zshenv.
"$*" is also something you'd do in sh/bash as they don't have any better way to do it. That joins the positional parameters with the first character of $IFS, whatever it is at the time. In zsh, rather than leaving it up to a roll of the dice, you can specify explicitly what separator to use when joining with the j parameter expansion flag: ${(j[ ])@} for instance to join the positional parameters with spaces.
| correct way of writing functions in zsh |
1,453,653,909,000 |
I'm using git aliases from zsh plugins: https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/git
So it has git aliases like:
gst # git status
ga # git add
gc "commit" # git commit -v "commit"
...
...and I'm also using git bare repo to backup all my dotfiles: https://github.com/Anthonyive/dotfiles/blob/0706bc81daa3aeb7899b506cd89d4ab78fc7b176/USAGE.md
In particular, the git bare repo technique aliases the git command to dotfiles:
alias dotfiles='git --git-dir=$HOME/.dotfiles/ --work-tree=$HOME'
alias d='dotfiles'
So then how do I map the all the git alias command to d? Like:
dst # similar to gst, but uses the dotfiles alias
da # similar to ga
dc "commit" # similar to gc "commit"
...
Mapping them one by one seems very tedious...
|
The associative array aliases contains all alias definitions.
for name in "${(@k)aliases}"; do
if [[ $name == g* && $aliases[$name] == 'git '* ]]; then
alias d${name#g}="dotfiles ${aliases[$name]#git }"
fi
done
Alternatively, you could change the d alias to a function that expects a following git command, but first expands shell aliases and removes any leading git.
alias d='d ' # expand aliases after d
function d {
if [[ $1 == "git" ]]; then shift; fi
dotfiles "$@"
}
Then d gst will run dotfiles status, d gc myfile will run dotfiles commit myfile, d ls-tree will run dotfiles ls-tree, etc. Completion is doable but not easily.
| Create new set of aliases based on current set of aliases (eg. gst -> dst)? |
1,453,653,909,000 |
When I switch from powerlevel9k to powerlevel10k, some extra space appears at the end of each line.
How can I remove this space?
|
According to this GitHub issue:
This difference is due to a bug Powerlevel9k that is too severe to
emulate in Powerlevel10k.
If you want your right prompt to be at the edge of the screen without
indentation, add ZLE_RPROMPT_INDENT=0 to your ~/.zshrc and restart
zsh. The default value of this parameter is 1, hence the space you are
seeing. This parameter is respected by all prompts except
Powerlevel9k.
| Upgrading to Powerlevel10k - Extra space at the end of line |
1,453,653,909,000 |
Is it possible to achieve the following
➜ ag editNote
src/store/actions.js
8:const editNote = ({ commit }, e) => {
26: editNote,
src/components/Editor.vue
5: @input="editNote"
22: 'editNote',
/frontend on master [✘!?]
➜ vi Ed
For example I would like to start typing vi Edit and get this replaced with
vi src/components/Editor.vue
|
The shell, whether bash or zsh, does not have access to the terminal scroll back buffer. While ag was running, output from it goes direct to the terminal and can't be intercepted by the shell.
Depending on what your terminal is, it may be possible to capture the contents of the scroll-back buffer. rxvt-unicode can be induced to dump it to a temporary file with the escape sequence '\e[0i'. For tmux, you can use tmux -q capture-pane \; save-buffer -b 0 $TMPFILE \; delete-buffer -b 0. And screen can do screen -X hardcopy $TMPFILE. However, all these solutions will only work from a local zsh session. As soon as you use ssh or similar, the temporary files won't be on the same system as zsh.
These temporary files can be used for a custom completion widget. I have such a widget but it is a bit too long to paste in here.
| ZSH - Autosuggest for the values output in the terminal window? |
1,453,653,909,000 |
I'm a long-time bash user just getting used to running zsh, oh-my-zsh, and powerline. I like the setup very much, but have one frustration I can't figure out how to solve.
I occasionally need to copy & paste terminal sessions into emails, text documents, etc. With the default powerline setup, the special characters cause grief, so my thought is to switch my zsh theme to a plain ascii theme. Unfortunately, I can't figure out how to do that from the command line. I'm sure it's possible, but I can't quite figure out the interaction between powerline and the shell to wire it up.
My suggested workflow would be:
Open shell session
Do work as normal
Switch themes to an "ascii only" theme (which powerline includes apparently)
Do work for copy/paste
Switch themes back to my previous one
I'm comfortable with scripting this as a script or alias, but I can't quite figure out how to start. My google-fu is weak when searching for things like "change powerline theme dynamically", "change zsh prompt dynamically", etc.
Things I've tried:
Manually setting the prompt: PS1="\$ ". That sets the left side prompt just fine, but doesn't clear the right side prompt (which usually has git information in my setup)
Manually applying a theme: source ~/.oh-my-zsh/themes/my-plain-ascii.zsh-theme. Still doesn't clear the right side prompt
And I'm still unsure how to re-apply my powerline defaults after I'm finished, short of source ~/.zshrc, which works, but seems heavyweight.
|
You should be able to source the ascii theme, then unset or clear the RPROMPT variable. So something like
source ~/.oh-my-zsh/themes/my-plain-ascii.zsh-theme
unset RPROMPT
<your work for copying and pasting>
source <powerline-install-directory>/bindings/zsh/powerline.zsh
Of course, you could always just add the unset RPROMPT line to your custom zsh-theme.
| Interactively switching zsh themes while running powerline |
1,453,653,909,000 |
I'm on freebsd (TrueOS, to be exact) and want to change my ZSH theme. ZSH was installed as binary package. I cloned the commonly known oh-my-zsh git repo, to gain themes, but want to stay with grml zsh config, which I downloaded from grml.org and placed into /usr/local/etc/zsh.
I'm sourcing /usr/local/etc/zsh/zshrc from my ~/.zshrc, and now I want to use a theme from ~/.oh-my-zsh (agnoster, to be exact, powerline and powerline-fonts are installed and working). But I have no idea ho to do this.
Please, how can I do this? I don't want to use OMZ. Just want to 'import' the theme(s).
|
Depending on the theme this can be rather tedious. Since they can depend on OMZ.
But luckily the theme you mentioned doesn't seem to be depending on any other code.
Just download the the theme from the Github page, save it under .zsh/themes, and add
source ~/.zsh/themes/agnoster.zsh-theme
to your .zshrc and it should work (As long as there is no conflict).
| apply zsh themes manually |
1,453,653,909,000 |
What exactly is the difference, operationally, between plugins and themes in oh-my-zsh? I.e. how would things break (if at all) if a plugin were instead put among the themes, or a theme among the plugins? Or is the distinction purely organizational?
|
Both the theme and the plugins are sourced in oh-my-zsh/oh-my-zsh.sh, so technically there should be no difference.
But a theme should only be used to change the appearance and a plugin is there to add new functionality.
With appearance I mean setting the values of $PS1, $PS2, $RPS1 and etc.
There are some plugins which also set some appearances, like the vi-mode plugin which sets the right hand side prompt ($RPS1) when it is not already set.
| difference between omz "plugins" and "themes"? |
1,453,653,909,000 |
I'm using ohmyzsh. I'm trying to load a diff themes base on the current directory path (pwd)
Logics
If pwd in or contain sustring /Sites/work/ load af-magic, else load robbyrussell.
.zshrc
I've tried
STR=$(pwd)
SUB='/Users/john/Sites/work'
if [[ "$STR" =~ .*"$SUB".* ]]; then
echo "It's there."
ZSH_THEME="af-magic"
else
ZSH_THEME="robbyrussell"
fi
Result
it kept loading robbyrussell
Ex.
|
If you look at the oh-my-zsh code, that ZSH_THEME variable is used by the oh-my-zsh initialisation code to source a per-theme file.
So if you want the theme to change whenever the current working directory lands in some directory, you need:
to change that variable whenever the current directory changes
reproduce that same sourcing of theme files when the variable changes.
So something like:
load-omz-theme() {
# copied and improved from oh-my-zsh
if (( $# > 0 )) ZSH_THEME=$1
if [[ -n $ZSH_THEME ]]; then
if [[ -f $ZSH_CUSTOM/$ZSH_THEME.zsh-theme ]]; then
source "$ZSH_CUSTOM/$ZSH_THEME.zsh-theme"
elif [[ -f $ZSH_CUSTOM/themes/$ZSH_THEME.zsh-theme ]]; then
source "$ZSH_CUSTOM/themes/$ZSH_THEME.zsh-theme"
else
source "$ZSH/themes/$ZSH_THEME.zsh-theme"
fi
fi
}
adapt-theme() {
local previous_theme=$ZSH_THEME
case $PWD in
($SUB*) ZSH_THEME=af-magic;;
(*) ZSH_THEME=robbyrussell;;
esac
[[ $ZSH_THEME = $previous_theme ]] || load-omz-theme
}
chpwd_functions+=(adapt-theme)
BTW, [[ "$STR" =~ .*"$SUB".* ]] is bash syntax, not zsh syntax. In zsh, quoting variables in regexps doesn't disable the regexp operators in it.
| Load specific ZSH_THEME base on specific directory contain specific string |
1,453,653,909,000 |
Consider the following screenshot
I'm using oh-my-zsh for shell customization. But due to the longer paths , I am unable to write longer linux commands. I want to change the prompt that only showing me the current directly keeping everything to the same.
Theme
ZSH_THEME="powerlevel9k/powerlevel9k"
Please help !
|
Powerlevel9k has been discontinued, see the note at the top of https://github.com/powerlevel9k/powerlevel9k. It's highly recommended to upgrade to Powerlevel10k.
Here's how to upgrade:
Add powerlevel10k to the list of Oh My Zsh themes.
git clone --depth=1 https://github.com/romkatv/powerlevel10k.git $ZSH_CUSTOM/themes/powerlevel10k
Replace ZSH_THEME="powerlevel9k/powerlevel9k" with ZSH_THEME="powerlevel10k/powerlevel10k" in ~/.zshrc.
sed -i.bak 's/powerlevel9k/powerlevel10k/g' ~/.zshrc
Restart Zsh.
exec zsh
Once you restart Zsh, prompt configuration wizard should start automatically. If it doesn't, type p10k configure. At some point the wizard will ask whether you want a one-line or a two-line prompt. The two-line version gives you a lot more room for typing commands, so you'll want to choose that. Two-line prompt usually wastes half of terminal's vertical space but with Powerlevel10k you have an option to enable Transient Prompt to avoid this downside.
In addition, you might want to add these lines to ~/.zshrc:
# My Windows home directory.
hash -d w=/mnt/c/Users/Pawar
This establishes bidirectional mapping between ~w and /mnt/c/Users/Pawar. Instead of /mnt/c/Users/Pawar/Downloads prompt will display ~w/Downloads. You can type cd ~w/Downloads instead of cd /mnt/c/Users/Pawar/Downloads, etc. Tab-completion understand this mapping, too. So cd ~w/Tab will work.
| Customize Shell Prompt Oh-my-zsh |
1,453,653,909,000 |
I am using oh-my-zsh and in oh-my-zsh there is a plugin called colord-manpages in the listing -
┌─[shirish@debian] - [~/.oh-my-zsh/plugins] - [10199]
└─[$] ll | grep colored
drwxr-xr-x 2 shirish shirish 4096 2015-12-30 14:27 colored-man-pages
This is the output of .zshrc -
─[$] grep -Ev '#' .zshrc
export ZSH=/home/shirish/.oh-my-zsh
ZSH_THEME="duellj"
plugins=(last-working-dir)
export PATH="/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games:/usr/local/lib:/usr/local/include/SDL2"
source $ZSH/oh-my-zsh.sh
and this is the output of ~/.oh-my-zsh/oh-my-zsh.sh script -
[$] grep -v '#' oh-my-zsh.sh
if [ "$DISABLE_AUTO_UPDATE" != "true" ]; then
env ZSH=$ZSH DISABLE_UPDATE_PROMPT=$DISABLE_UPDATE_PROMPT zsh -f $ZSH/tools/check_for_upgrade.sh
fi
fpath=($ZSH/functions $ZSH/completions $fpath)
autoload -U compaudit compinit
: ${ZSH_DISABLE_COMPFIX:=true}
if [[ -z "$ZSH_CUSTOM" ]]; then
ZSH_CUSTOM="$ZSH/custom"
fi
if [[ -z "$ZSH_CACHE_DIR" ]]; then
ZSH_CACHE_DIR="$ZSH/cache"
fi
for config_file ($ZSH/lib/*.zsh); do
custom_config_file="${ZSH_CUSTOM}/lib/${config_file:t}"
[ -f "${custom_config_file}" ] && config_file=${custom_config_file}
source $config_file
done
is_plugin() {
local base_dir=$1
local name=$2
test -f $base_dir/plugins/$name/$name.plugin.zsh \
|| test -f $base_dir/plugins/$name/_$name
}
for plugin ($plugins); do
if is_plugin $ZSH_CUSTOM $plugin; then
fpath=($ZSH_CUSTOM/plugins/$plugin $fpath)
elif is_plugin $ZSH $plugin; then
fpath=($ZSH/plugins/$plugin $fpath)
fi
done
if [[ "$OSTYPE" = darwin* ]]; then
SHORT_HOST=$(scutil --get ComputerName 2>/dev/null) || SHORT_HOST=${HOST/.*/}
else
SHORT_HOST=${HOST/.*/}
fi
if [ -z "$ZSH_COMPDUMP" ]; then
ZSH_COMPDUMP="${ZDOTDIR:-${HOME}}/.zcompdump-${SHORT_HOST}-${ZSH_VERSION}"
fi
if [[ $ZSH_DISABLE_COMPFIX != true ]]; then
if ! compaudit &>/dev/null; then
handle_completion_insecurities
else
compinit -d "${ZSH_COMPDUMP}"
fi
else
compinit -i -d "${ZSH_COMPDUMP}"
fi
for plugin ($plugins); do
if [ -f $ZSH_CUSTOM/plugins/$plugin/$plugin.plugin.zsh ]; then
source $ZSH_CUSTOM/plugins/$plugin/$plugin.plugin.zsh
elif [ -f $ZSH/plugins/$plugin/$plugin.plugin.zsh ]; then
source $ZSH/plugins/$plugin/$plugin.plugin.zsh
fi
done
for config_file ($ZSH_CUSTOM/*.zsh(N)); do
source $config_file
done
unset config_file
if [ "$ZSH_THEME" = "random" ]; then
themes=($ZSH/themes/*zsh-theme)
((N=(RANDOM%N)+1))
RANDOM_THEME=${themes[$N]}
source "$RANDOM_THEME"
echo "[oh-my-zsh] Random theme '$RANDOM_THEME' loaded..."
else
if [ ! "$ZSH_THEME" = "" ]; then
if [ -f "$ZSH_CUSTOM/$ZSH_THEME.zsh-theme" ]; then
source "$ZSH_CUSTOM/$ZSH_THEME.zsh-theme"
elif [ -f "$ZSH_CUSTOM/themes/$ZSH_THEME.zsh-theme" ]; then
source "$ZSH_CUSTOM/themes/$ZSH_THEME.zsh-theme"
else
source "$ZSH/themes/$ZSH_THEME.zsh-theme"
fi
fi
fi
Can anybody tell/share what I should be doing so that colored-manpages function the moment I use zsh as my xterm ?
I tried googling but couldn't find anything :(
|
Just add the plugin to the plugins definition in .zshrc:
plugins=(last-working-dir colored-man-pages)
Then start a new shell and you'll see the plugin activated.
| How do I add colored-manpages plugin to my zsh profile (using oh-my-zsh)? |
1,453,653,909,000 |
#Get client IP base on current logged in user
if [ $USER == 'root' ]
then
ip="$(last | awk 'NR==1 {print $3}')"
else
ip="$(echo $SSH_CONNECTION | cut -d " " -f 1)"
fi
/root/.bashrc:157: = not found
Line 157
Note
I appended this line source ~/.bashrc to my .zshrc to
vi .zshrc
source ~/.bashrc # import all my quick aliases and fns
|
In zsh, =cmd is a filename expansion operator that expands to the path of the cmd command. =cmd is similar to $commands[cmd].
So here, with == in one of the arguments of the [ command, that expands it to the path of the = command. As there's no command called = in your $PATH, that causes an error.
Compare:
$ echo =ls
/bin/ls
$ echo =junk
zsh: junk not found
The equality operator in the [ command is =. The [ command only does tests, it doesn't do any assignments, so there's no need to differentiate between an assignment operator and an equality comparison operator like there is in some other languages (with = vs == like in C or := vs = in some others, etc).
So it should just be:
[ "$USER" = root ]
Still the [ of zsh, like that of ksh also supports == as an alternative to =, but unless you disable the equals option (like it is in ksh emulation), you'd need to quote at least the first = to avoid that =cmd operator:
[ "$USER" '==' root ]
Note that while $USERNAME is automatically set by zsh, $USER is not (though it is set as an environ variable by some things like login).
To test whether you have superuser privileges, it's more robust to check that your effective user id is 0, which can be done in zsh or bash with [ "$EUID" -eq 0 ] or (( EUID == 0 )).
See also:
What's the difference between single and double equal signs (=) in shell comparisons?
| /root/.bashrc:157: = not found |
1,453,653,909,000 |
When i installed zsh and add oh-my-zsh i cant execute command like ifconfig and services.
To install zsh i execute this commands:
$ sudo apt-get install zsh
$ wget https://github.com/robbyrussell/oh-my-zsh/raw/master/tools/install.sh -O - | zsh
$ chsh -s `which zsh`
My .zshrc look like this:
# If you come from bash you might have to change your $PATH.
export PATH=$HOME/bin:/usr/local/bin:$PATH
# Path to your oh-my-zsh installation.
export ZSH=/home/kuchar/.oh-my-zsh
# Set name of the theme to load. Optionally, if you set this to "random"
# it'll load a random theme each time that oh-my-zsh is loaded.
# See https://github.com/robbyrussell/oh-my-zsh/wiki/Themes
ZSH_THEME="af-magic"
# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"
# Uncomment the following line to use hyphen-insensitive completion. Case
# sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"
# Uncomment the following line to disable bi-weekly auto-update checks.
# DISABLE_AUTO_UPDATE="true"
# Uncomment the following line to change how often to auto-update (in days).
# export UPDATE_ZSH_DAYS=13
# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"
# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"
# Uncomment the following line to enable command auto-correction.
# ENABLE_CORRECTION="true"
# Uncomment the following line to display red dots whilst waiting for completion.
# COMPLETION_WAITING_DOTS="true"
# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"
# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# HIST_STAMPS="mm/dd/yyyy"
# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder
# Which plugins would you like to load? (plugins can be found in ~/.oh-my-zsh/plugins/*)
# Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(git)
source $ZSH/oh-my-zsh.sh
# User configuration
# export MANPATH="/usr/local/man:$MANPATH"
# You may need to manually set your language environment
# export LANG=en_US.UTF-8
# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
# export EDITOR='vim'
# else
# export EDITOR='mvim'
# fi
# Compilation flags
# export ARCHFLAGS="-arch x86_64"
# ssh
# export SSH_KEY_PATH="~/.ssh/rsa_id"
# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"
When i execute PATH=$HOME/bin:/usr/local/bin:$PATH nothing change, still cant use ifconfig and service.
|
Solution for this problem:
Change this in your zsh config file ~/.zshrc
export PATH=$HOME/bin:/usr/local/bin:$PATH
to this:
export PATH=$HOME/bin:/usr/local/bin:/sbin:/usr/sbin:$PATH
Save and reboot for sure.
| zsh: command not found: services |
1,453,653,909,000 |
I use ZSH with Oh My Zsh. I would like each new ZSH shell to start with an empty history. Commands typed in one shell should never show up in the history of another shell. How can I achieve this?
I've tried appending the following to my ~/.zshrc to no avail:
setopt no_share_history
unsetopt share_history
unsetopt inc_append_history
unsetopt append_history
I have also tried following this answer to make the arrow keys only show local history, but that seemed to have no effect.
Currently, if I open a new shell, it imports history. I cannot seem to delete the history; when I delete ~/.zsh_history, it re-appears with the entire old content once I open a new shell. inc_append_history does prevent history from being written right away, but the history will still eventually be saved once the shell is closed.
|
The zsh history is only saved if you set both the HISTFILE variable (to the path of the history file) and SAVEHIST variable (to the amount of entries to store there).
So it should only be a matter of removing those variable definitions from wherever they're being set (probably your ~/.zshrc or any file included from there). Even not setting only one of them would be enough.
Note that setopt no_share_history and unsetopt share_history (or set +o nonosharehistory, etc or options[sharehistory]=off) are strictly equivalent.
| How can I configure ZSH to start each shell with an isolated, empty history? |
1,453,653,909,000 |
So today I wanted to add some extra alias to zsh.
I did the usual
nano ~/.zshrc
and added my alias
ex:
alias desktop="cd desktop"
(I've doubled checked that all variables for typos)
Ctrl+O to save and Ctrl+X to exit.
After getting out I run:
source ~/.zshrc
And get the following error:
/Users/fridavbg/.zshrc:116: unmatched "
When running I get:
echo $SHELL
/bin/zsh
Any kind soul out there that could help me out or give me some resource that might help me figure out how to fix this?
It feels like this is something simple, but I'm a little scared to mess my path up completely.
|
Your error message is not unmatched, it is unmatched ", as in there is an unmatched quote character, ".
The part /Users/fridavbg/.zshrc:116 exlains that this error was detected in file /Users/fridavbg/.zshrc on line 116.
So you should look at that file around the indicated line for unmatched quotes. Note that sometimes the indicated line is not the line where there error is. If you don't find an error on the indicated line, it may be before that line, or sometimes after that line.
Example:
command1 "missing quote at the end
command2 ""
Here the quote started on the first line continues to the first quote character on the second line, and the quote starting with the second quote character is not terminated.
| zsh: When running source I get zshrc:116: unmatched |
1,486,900,441,000 |
Yank doesn't clear the killring, so it gets cluttered after a while. Can I clear it?
I'm using Oh My Zsh.
|
The size of the kill ring is determined by the length of the killring array. This is 8 by default.
The variable is only available in zle widgets, so you can't manipulate it on the command line, you have to define a widget and invoke it either through a key binding or through M-x. Here's an example of a widget that blanks the killring.
set_killring_size () {
local empty=
if ((!$+NUMERIC)); then
# Wipe killring and re-create it to its current size
NUMERIC=$#killring
killring=()
fi
if ((NUMERIC <= $#killring)); then
# Truncate killring to the specified size
killring=("${(@)killring[1,$NUMERIC]}")
else
# Grow killring to the specified size
killring=("${(@)killring}" "${(@s:_:)${(l:$((NUMERIC-$#killring-1))::_:)empty}}")
fi
}
zle -N set_killring_size set-killring-size
Call this widget with no argument to wipe the killring: M-x set-killring-size RET. Call it with a numeric prefix to set the killring size: ESC 4 2 M-x set-killring-size RET.
| can I clear current killring in zsh? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.