如何将微信和WordPress关联起来

WordPress 自动使用文章ID作为别名(slug)

from:https://www.wpdaxue.com/wordpress-using-post-id-as-slug.html

最近有朋友一直在问:我使用固定链接结构是 %post_id% (ID),但是 WP User Frontend 这个前端用户中心插件要求必须设置为 %postname% (slug)才能使用,我不想改变以前的文章链接地址,该怎么办?

本文就是解决这个问题的,让 WordPress 自动使用文章ID作为别名(slug),也就是说,即使你设置为 %postname% 结构,仍旧可以自动生成 ID 结构的链接。或许你会说,修改固定链接结构后,原来的那些文章的链接变化了,怎么办?不用担心,照样可以解决!进入正题!

为了安全起见,请先备份网站的数据库,然后再按照下文操作!

更改固定链接结构

假设你原来的固定链接结构设置为 /%post_id%,现在你可以将它改为 /%postname% ,这时候你会发现,新建文章和老文章都使用文章标题作为别名

批量修改老文章的别名为ID

将下面的代码添加到网站根目录的 wp-config.php 的最底部,保存后访问一次网站首页(你将看到浏览器一直都在努力打开网页,不要急,耐心等待,直到网页真正打开,所需时间看文章数和网络情况而定)。网页打开后,删除刚刚添加到 wp-config.php 的代码!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
 * 批量更改旧文章的别名为ID
 * 使用方法:将代码添加到网站根目录的 wp-config.php 的最底部,访问一次网站首页,等页面打开后,再删除这些代码
 * https://www.wpdaxue.com/wordpress-using-post-id-as-slug.html
 */
// 添加一个变量来包容文章标题数组,防止重复操作
$slug_done = array();
// 查询所有文章
$posts = $wpdb->get_results( "
	SELECT
	`ID`,
	`post_title`
	FROM
	`" . $wpdb->posts . "`
	WHERE
	`post_type` = 'post'
	" );
// 输出文章
foreach( $posts AS $single ) {
	$this_slug = $single->ID;
	$slug_done[] = $this_slug;
    //  使用文章ID替换文章原来的别名
	$wpdb->query( "
		UPDATE
		`" . $wpdb->posts . "`
		SET
		`post_name` = '" . $this_slug . "'
		WHERE
		`ID` = '" . $single->ID . "'
		LIMIT 1
		" );
}

新文章自动使用ID作为别名

将下面的代码添加到主题的 functions.php ,新建的文章都会自动使用ID作为别名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
 * 新文章自动使用ID作为别名
 * 作用:即使你设置固定连接结构为 %postname% ,仍旧自动生成 ID 结构的链接
 * https://www.wpdaxue.com/wordpress-using-post-id-as-slug.html
 */
add_action( 'save_post', 'using_id_as_slug', 10, 2 );
function using_id_as_slug($post_id, $post){
	global $post_type;	if($post_type=='post'){ //只对文章生效		// 如果是文章的版本,不生效
		if (wp_is_post_revision($post_id))
			return false;
		// 取消挂载该函数,防止无限循环
		remove_action('save_post', 'using_id_as_slug' );
		// 使用文章ID作为文章的别名
		wp_update_post(array('ID' => $post_id, 'post_name' => $post_id ));
		// 重新挂载该函数
		add_action('save_post', 'using_id_as_slug' );
	}}

2013-10-19更新:添加文章类型判断,只对文章(post)生效,不会影响页面等其他类型

参考资料:

http://www.ryankessen.com/50/how-to-mass-change-article-slug-urls-in-wordpress/

http://wordpress.stackexchange.com/questions/51363/


 

 

如何将微信和WordPress关联起来

实现微信账号与WordPress账号的绑定

from:http://www.powerxing.com/wechat-account-link-to-wordpress/


 

WordPress上已经有不少能实现微信订阅号/公众号连接WordPress的插件,如微信公众订阅号插件、连接微信、微信机器人等,可以实现两者的内容同步,也可以自定义关键词回复,推送相关文章。

不过这类插件还没有实现的一个功能就是微信的账号跟WordPress账号的绑定,若用WordPress二次开发一些带有会员功能的公众号,往往需要以微信的账号(openid)作为WordPress的账号,这样在获取微信授权后,就可以直接实现登陆,省去用户再注册账号的繁琐步骤。

实现的流程很简单:

  1. 若用户未登陆,则引导用户访问微信oauth2授权页面,取得code
  2. 通过code换取网页授权access_token
  3. 返回access_token的同时已经返回了openid,通过openid就可以登陆了。
  4. 通常我们还需要用户的昵称头像等信息,因此用户首次访问时,需要再通过access_token获取基本信息,再通过这些基本信息创建一个WordPress用户。创建用户之后,以后的登陆只需要进行到第3步即可。

微信用户的信息获取查看官方API文档(http://mp.weixin.qq.com/wiki/index.php?title=网页授权获取用户基本信息)即可,通过使用WprdPress提供的函数,可以很方便的实现上述流程。

主要应用到了 PHP 的 cURL 来进行api的通信,然后通过 WordPress 函数 wp_insert_user() 创建新用户、函数 wp_set_current_user()wp_set_auth_cookie() 实现用户登陆。

PHP代码如下:

  1. function power_user_is_login() {
  2. $appID = ;
  3. $appsecret = ;
  4. $wechat_token = ; // 开发中心的token
  5.  
  6. // 排除跳转至oauth2的页面
  7. if ( strpos($_SERVER[“REQUEST_URI”], ‘wp-login.php’) !== false || strpos($_SERVER[“REQUEST_URI”], $wechat_token) !== false ) return;
  8.  
  9. if (!is_user_logged_in()) {
  10.  
  11. if ( isset($_GET[‘code’]) ) {
  12. $code = $_GET[‘code’];
  13. $url = ‘https://api.weixin.qq.com/sns/oauth2/access_token?appid=’.$appID.‘&secret=’.$appsecret.‘&code=’.$code.‘&grant_type=authorization_code’;
  14.  
  15. $ch = curl_init();
  16. curl_setopt($ch, CURLOPT_URL, $url);
  17. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  18. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  19. curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  20. $json = curl_exec($ch);
  21. $json = json_decode($json);
  22.  
  23. if ( isset($json->errcode) ) {
  24. header(“Content-type: text/html; charset=utf-8”);
  25. echo ‘系统出错,获取用户信息失败,请重试’; exit();
  26. }
  27.  
  28. $access_token = $json->access_token;
  29. $openid = $json->openid;
  30.  
  31. if ( !username_exists($openid) ) {
  32. $url = ‘https://api.weixin.qq.com/sns/userinfo?access_token=’.$access_token.‘&openid=’.$openid.‘&lang=zh_CN’;
  33. curl_setopt($ch, CURLOPT_URL, $url);
  34. $json = curl_exec($ch);
  35. $json = json_decode($json);
  36.  
  37. if ( isset($json->errcode) ) {
  38. header(“Content-type: text/html; charset=utf-8”);
  39. echo ‘系统出错,获取用户基本信息失败,请重试’; exit();
  40. }
  41.  
  42. $avator = $json->headimgurl;
  43. if (!$avator) $avator = ;
  44. if (substr($avator, 2) == ‘/0’) {
  45. $avator = substr($avator, 0, 2).‘/132’;
  46. }
  47.  
  48. $userdata = array(
  49. ‘user_login’ => $openid,
  50. ‘display_name’ => $json->nickname,
  51. ‘user_url’ => $avator,
  52. ‘user_pass’ => NULL,
  53. );
  54.  
  55. $user_id = wp_insert_user( $userdata ) ;
  56.  
  57. //On success
  58. if( is_wp_error($user_id) ) {
  59. echo ‘系统出错,创建用户失败,请重试’; exit();
  60. }
  61.  
  62. }
  63.  
  64. $user = get_userdatabylogin($openid);
  65. $user_id = $user->ID;
  66.  
  67. wp_set_current_user($user_id, $openid);
  68. wp_set_auth_cookie($user_id);
  69.  
  70. curl_close($ch);
  71.  
  72. } else {
  73. $site_uri = site_url();
  74. $redirect_uri = urlencode($site_uri.$_SERVER[“REQUEST_URI”]);
  75. $scope = ‘snsapi_userinfo’;
  76. $url = ‘https://open.weixin.qq.com/connect/oauth2/authorize?appid=’.$appID.‘&redirect_uri=’.$redirect_uri.‘&response_type=code&scope=’.$scope.‘&state=login#wechat_redirect’;
  77.  
  78. header(“Location: “.$url);
  79. exit();
  80. }
  81. }
  82. }
  83.  
  84. add_action( ‘init’, ‘power_user_is_login’);
php

补充appid等信息,然后将代码复制到主题中的function.php中,用户未登陆时,访问任一页面则会跳转到微信oauth2页面。用户验证登陆成功后,会返回到该页面中。

如何将微信和WordPress关联起来

如何将WordPress与微信公众平台关联(一)

from:http://jingyan.baidu.com/article/2a138328992196074a134fbf.html


 

对于拥有自己独立的WordPress网站的用户来说,通过几步设置就可以将自己的WordPress网站与纵横微信机器人绑定起来。

方法/步骤

  1. 1

    1、将微信公众号与纵横微信机器人关联起来。

    2、将纵横微信机器人与WordPress网站关联起来。

    已经安装了微信机器人插件的用户可以直接跳过这一步。

    如果之前没有安装过微信机器人,在网站后台点击“插件”——“安装插件”

    如何将微信和WordPress关联起来
    如何将微信和WordPress关联起来
  2. 2

    搜索:denishua,并安装微信机器人插件备注:微信机器人是免费的插件,旁边的微信机器人高级版是付费插件。安装免费的微信机器人即可。

    如何将微信和WordPress关联起来
    如何将微信和WordPress关联起来
  3. 3

    3、在纵横微信机器人后台,“微信”——“设置”——“第三方平台”里面,勾选“第三方平台(1)搜索”,在下面相应的位置填写自己的网址与微信机器人的Token,然后点击“保存设置”。

    如何将微信和WordPress关联起来
    如何将微信和WordPress关联起来
  4. 4

    4、在公众号里面搜索自己网站的里面的关键词。(建议多试几个不同的关键词)

    如何将微信和WordPress关联起来
    如何将微信和WordPress关联起来
  5. 5

    通过微信公众号可搜索到自己WordPress网站的文章内容,即表示设置成功。这样就将你的网站与纵横微信机器人关联起来,关注你公众号的用户输入关键词就可以搜索到网站的文章内容了。

 

 

WordPress vs Joomla vs Drupal? + CMS comparison chart. Which one is the best?

from: http://websitesetup.org/cms-comparison-wordpress-vs-joomla-drupal/

The best websites today are powered by easy to use content management systems (CMS) that allow you to make changes to a website without needing to touch a single line of code.

If you want to get a new, powerful website online, but can’t wait around or shell out the big bucks ($3k+) required for a custom site, look no further than these three options.

WordPress, Joomla and Drupal all offer great features, tons of customizaions, ease-of-use, and strong security.

Drupal, Joomla and WordPress compared
Drupal, Joomla and WordPress compared

Oh yeah, all three are also free.

Choosing the right one can be difficult because they’re all good options.

But chances are, one of these three will fit your unique situation the best (whether that’s firing up a simple business website or running a fully functioning social network).

Let’s see how they compare to find the perfect choice for you.

Quick Overview:

  • WordPress – Best choice for beginners because of it’s ease-of-use, it works especially well for small to medium sized websites, blogs and smaller e-commerce stores.
  • Joomla – Great for e-commerce or social networking websites, but requires a basic understanding of technical skills.
  • Drupal – The most difficult, but also the most powerful. It requires a familiar understanding of HTML, CSS and PHP.

CMS Comparison Chart

WordPress, Joomla or Drupal?
WordPress, Joomla or Drupal?

Which one is the right for your needs? Read our in-depth review to find out.

WordPress


WordPress is the world’s most popular content management system.

Despite it’s humble blogging beginnings, WordPress has taken the world by storm (literally), powering over over 60 millions websites today.

If that’s not impressive, WordPress is also used on over 40% of CMS-based websites– leading the market of DIY CMS websites by a wiiiiiiide margin.

Here’s why it’s so popular.

  • Easy to Install – Many web hosting companies (like Bluehost) offer instant, automated WordPress installs. That means you can get a brand new website up-and-running in less than five minutes! (It takes longer to go brew a cup of coffee than it does to have new WordPress website online.)
  • Customizable – WordPress has significantly more plug-ins, themes and other customizations available than any other CMS. Because of it’s widespread popularity, more third-party designers and developers will create free (or relatively inexpensive) new WordPress tools to help you create/start a blog that looks like a high-dollar custom website (while only setting you back less than $100).
  • Free– WordPress is absolutely, no-strings-attached free to use. And building on the last point, there are easily tens of thousands of free plug-ins and themes available to choose from. This is perfect for most beginners putting together their first site because it keeps costs down.
  • Community Support – If you do experience issues or have questions about your new WordPress site, you can easily tap into the millions of people already using and supporting it. Their support forum includes helpful contributors that can answer any question you might have, within minutes, again – for free. Awesome, right?

Of course, WordPress isn’t perfect and does have it’s drawbacks.

Cheif among them: WordPress is an easy-to-use framework because it locks down the ability for most users to make significant visual edits (for their own good). So you can’t make a TON of structural website changes without the help of a designer and/or developer.

However, for a beginner, this is probably the most suitable platform to build a site.

Drupal


Drupal is the second most popular content management system available today, used by sites both large and small.

It’s among the most powerful open sourced options available, which means it’s learning curve is also a bit steeper.

Here’s where Drupal excels:

  • Technically Advanced – Drupal is the most technically advanced of these three content management systems. Good for technical people who like to get their hands dirty.
  • Improved Performance – Drupal pages typically load more quickly, and have faster response times than those made with WordPress or Joomla. Part of the reason is because it’s less resource-intensive, requiring a less expensive server or hosting setup. (However like with all CMS, adding too many third party plugins can bog down performance.)
  • Customizable – Drupal is easy to customize with many widely available plug-ins, themes and other configurable options to choose from. You can also edit the root files directly, perfect for those developers who need to make more significant changes.
  • Free – You can download the Drupal software for free, and install it on your own hosting server.

Drupal is the most powerful content management system out of the box. But with that power comes some additional difficulties for the website owner.

Anyone considering Drupal should have at least a basic knowledge of HTML, PHP and other common web programming languages. You don’t need to be an expert necessarily, but being able to troubleshoot error messages and identify code problems will be a HUGE benefit.

If your website begins to gain traction, evolving beyond a simple business site or site, you’ll need to have (or hire) technical expertise to make sure it continues to run smoothly.

Which can be a bit of a problem, because it’s typically a little harder (and more expensive) to find someone with advanced knowledge of Drupal’s steep learning curve. Whereas it should be much easier and less expensive to find someone relatively tech-savvy to help you make basic WordPress updates.

Also, unlike WordPress.com, there is no option to have a website hosted by Drupal themselves. That means purchasing your own domain and hosting is required before getting started with a new Drupal site.

Joomla


Joomla is like the compromise between WordPress and Drupal.

It’s powerful enough to run most websites without any problems, and it doesn’t require the same level of technical experience to run as Drupal either.

As the second most used CMS (behind WordPress), Joomla also has a lot of plug-ins and themes available to choose from (around 6000 or so)similar to both WordPress and Drupal. So customizing the look and feel of your site shouldn’t be problem.

Here are a few more reasons Joomla might be ideal for you:

  • Social Networking – Joomla makes creating social networks of all three options. Social networks can be a powerful asset for many sites, and with Joomla, you can have one up and running extremely quickly and easily.
  • Commerce Sites – Joomla also makes setting up an online store quick and painless. You can setup eCommerce shops with both Drupal and WordPress, but it tends to require more effort and special customizations.
  • Not too Technical – Joomla has found the middle ground between the ease of managing a WordPress website and the power of a Drupal site. The good news is that most non-tech savvy people should be able to run a great Joomla site without needing any technical support.
  • Help Portal – Joomla offers a great help portal for asking questions and getting technical support. It’s not fast or extensive as WordPress’ community-based support pages, but is definitely quicker (and cheaper) than Drupal’s technical support options.
  • Free – Like both WordPress and Drupal, Joomla is another free option to use on your own web servers. However similar to Drupal, there is no option to have it hosted for free like WordPress offers.

Joomla users love that their websites can do or be almost anything, without sacrificing ease-of-use. Joomla has brilliantly combined the power and flexibility Drupal has to offer, while also retaining the intuitive, user-friendliness that WordPress excels at, making it a perfect middle ground in a crowded marketplace.

Making Your Choice

Everyone will say their content management system is the best. All three are excellent choices in most cases.

But your own unique scenario will require different capabilities, which probably makes ONE of these three CMS options the perfect fit.

Looking to get started quickly with a simple business website or blog? Look no further than WordPress.

If you have high hopes from day one that your site will grow significantly, requiring extensive features and unlimited customizations, take the plunge with Drupal.

Split between those two options, or need something unique like a social network or eCommerce site, Joomla might be the best bet.

All three platforms are free.

Each offers a variety of helpful third-party tools to add unique features to your site.

And you’ll find readily available technical support with each one (although Drupal’s might be among the most expensive).

Is It Possible to Migrate From One to Another?

There’s no wrong option per se.

However, if you feel like you made the wrong choice and want to switch down the road, it is relatively easy to migrate from one to another.

Just make sure you have both the time and expertise readily available to make sure there are no problems during the site transfer.

My Favorite Choice Is…

I’ll be honest.

I like WordPress.

My own site (this one you’re currently reading) is built on WordPress.

It’s super easy to add new content and there are tons of free plugins and layouts to choose from so I can easily change and tweak basically anything I want without needing to know HTML, CSS, or any other programming languages. It also has a ton of security updates and features, so it’s nice knowing that other professionals have my back.

If you’re just starting out, go with WordPress.

Chances are, you’ll never leave (even when your site has tons of posts and truckloads of visitors).

What Do the Experts Say?

You’ve read my opinion.

But how about some other industry professionals who work with all three CMS choices on a daily basis?

I reached out to a few developers from large agencies who frequently work with WordPress, Joomla and Drupal, asking them all a very simple question:

“What is the best CMS (WordPress, Joomla or Drupal) for a beginner?”

#1 Marcus Neto from Blue Fish Design Studio:

“I would have to say that if I was mentoring a beginner I would suggest WordPress. WordPress seems to have a vibrant community.”

“They have brand recognition with people outside of the technical market. There are a lot of plugins for WordPress. But, unfortunately, creating your own themes from scratch with WordPress will require a reasonable knowledge of PHP. Second would be Joomla. Third would be Drupal. Drupal is just too complex. It is the best of the three. But it has a steep learning curve that most would not be able to handle.”

#2 James George from Creative Beacon:

“That’s a great question. If you ask me, it would have to be WordPress, hands down, no contest. With most hosting providers providing one-click installs of the database and main WordPress files, all you have to do is log in, pick a theme, and fill out information. Some themes are more advanced, like the ones you will find on Themeforest, but for beginners, WordPress really isn’t that difficult to set up.”

“If you can fill out a form and click a few buttons, you can set up and run a WordPress site. Writing articles and placing images in each post is intuitive, and if you need more functionality, there are millions of plugins out there that you can install and have up and running in minutes. WordPress is quick, easy and requires no real knowledge of web design or web development. Even the advanced themes can be set up by a novice if they are good at following instructions. WordPress have my vote by a mile!”

#3 Mark Atkinson from Red Giant Design:

“For beginners, I would definitely lean towards WordPress being the one which will most likely satisfy the needs of the individual. Of course, it always depends on what your endgame is – what purpose the site is meant to serve. Seeing that WordPress provides great SEO out the box and has a bunch of easy-to-use plugins and themes, as well as the fact that WordPress is infinitely easier to update and maintain than its competitors, I feel that WordPress provides the most complete solution for a beginner looking to build a new website.”

#4 Jeff Clark from Codeless Interactive:

“WordPress – no question. It’s the most user-friendly of all three options (by a long shot). The community support is fantastic, so it’s easy to find knowledgeable people who’ve already experienced what you’re trying to do (or fix). And it’s WAY more powerful than people think.”

“Most people are still under the misconception that WordPress is still only a limited option for blogs. It’s not. I’ve built everything from enormous eCommerce websites and large hotel websites to well-known fashion blogs that get tens of thousands of visits each month. It’s become a much better well rounded CMS over the past few years, and can handle the majority of use cases at any scale.”

Run a web design/development agency? Perhaps you’re a freelancer? Shoot me an email and chime in with your thoughts.

 

Have you made your choice yet? If so, dive in today and start building your website. I’ve put together the following guides that can help:

P.S. If you get stuck while setting up your website, get in touch with me and I’ll get back to you as I’m currently offering free consultation and advice via email.

P.P.S. Want more reading? Go and check this article: How WordPress took the CMS crown from Joomla and Drupal.

Comments? Leave them below – let’s discuss!

解决在MACBOOK中打开CSV文件的乱码问题(其它文件类型同样适用)

乱码原因:CSV文件里头估计是没有带文字编码的信息,所以Macbook用默认的编码打开时,出现乱码的问题。

解决方案:
1,启动Excel,新建一个空文件
2,File -》 import
3,选择要打开的CSV文件
4,在Text Import Wizard step1 of 3 的导航窗口里,调整 File origin 选项里的文字编码
   是 Simplified Chinese (Windows,DOS)

Mac OS X Terminal 101:终端使用初级教程

转帖:https://www.renfei.org/blog/mac-os-x-terminal-101.html

 

最近学习苹果认证的《Mac OS X Support Essentials》教程,看到 Command Line 一节有很多实用的知识,下面选取一部分翻译 + 笔记,整理成此文。

你可以整天驾驶汽车而不用知道如何修理它们,但是如果你希望当一个维护员,你就需要知道事情是如何运作的。同样的事情也发生在了 Mac OS X 上;你可以一直使用 Mac 而不用知道如何修理它,但是如果你想对系统做一些维护或解决一些问题,那么你需要知道如何使用 command-line。

为什么要使用命令行/如何开启命令行?

  • 许多功能在图形界面不提供,只有通过命令行来实现。
  • Finder会隐藏许多你不太会需要的文件,然而 command line 会允许你访问所有文件。
  • 通过 command line 可以远程访问你的 Mac(利用 SSH)。
  • administrators 用户可以通过 sudo 命令获得 root 用户权限。
  • 通过 command-line script 可以使工作更高效。
  • Terminal(终端)程序可以在“实用工具”里找到。
  • 如果你开启手动输入用户名登陆模式,登陆时在用户名处输入 >console 可以直接进入命令行界面。随后你仍然需要登录到一个账户。

初识Command Line

  • 许多命令会花费一些时间来执行,然而这中间不会给出任何提示或者进度条。一般结束后会出现一个“用户名$”的标记。如果没有出现,那么说明最后一条命令正在执行。
  • 一条命令包括 Command Name、Options、Arguments、Extras 四个部分,但是后三个部分有时是可选的。Options 部分用-作为前导符。其中许多命令的 Options 部分只包含单个字母,这时可以合并。例如,ls -lAls -l -A是等效的。Arguments 部分用来细化这个命令或指定这个命令具体的实施对象,Extras 部分则用来进一步实现其他功能。
  • 举例:下列命令包含前三个部分,用于删除 Junk 这个程序。

    michelle$ rm -R /Applications/Junk.app

  • 如果你输入了一些错误的命令,系统会返回一些错误信息。但是系统却不会阻止你做傻事(例如删除整个用户文件夹)。

关于 man 命令

虽然有上千条命令,每条命令还有许多可选参数和具体的使用方式,但是你却不需要记住这些命令。你只需要记住一个:man

大多数命令都会包含一个使用指南,会告诉你任何你需要知道的关于这个命令的所有细节,在命令行中输入 man command-name 即可获取。例如,你想知道ls这个命令怎么使用,输入man ls即可进入使用指南页面。

使用指南往往很长,所以你可以使用(上箭头)或(下箭头)来上下移动,使用 来翻页,输入/和关键字来按照关键字搜索,按Q来退出使用指南页面。

那么——如果你连命令名称都不知道怎么办呢?输入man -k和关键字来对整个使用指南数据库进行搜索。

命令行,文件和路径

如果知道如何使用命令是掌握 command line 的第一步,那么第二步就是学习如何在 command line 中使用文件路径。如果你掌握了文件路径,你将会发现这比使用 Finder 更加快捷。

注意

  • command line 工具是大小写敏感的,并且对于文件名,必须包括扩展名。例如,你想找iTunes这个程序,输入itunes是无效的,必须输入iTunes.app
  • Mac OS传统上喜欢使用“文件夹”(folders)这个名称,但是在 command line 中,主要使用“目录”(directory)这个词。这和 UNIX 是一致的。

两种路径:绝对路径和相对路径

  • 绝对路径:完整描述一个文件的位置,总是以斜杠(/)(forward slash)开头。例如/Users/michelle/Public/Drop Box
  • 相对路径:只描述一部分位置信息,它和你在 command line 目前的目录有关。当你打开新的 Terminal 程序时,command line 会话的目录应该是你的 home folder。这时上面例子文件夹的相对路径写作Public/Drop Box。显然它从当前目录开始。和html类似,你也可以使用两个点(“..”)来代表父目录,这样你就可以用相对路径表示上级或同级目录了。例如你可以输入cd ..甚至cd ../..

切换到其他路径和目录

如果你想将当前 command line 会话切换到其他目录,需要用到三个命令:pwdlscd

  1. pwd的含义是“print working directory”,会显示当前目录的绝对路径。
  2. ls的含义是“list directory contents”,它会列出当前目录的内容。这个命令还有其他参数可选。
  3. cd的含义是“change directory”,它会改变当前目录到你指定的目录。如果你不指定,则会返回你的 home folder。

处理特殊字符

如果目录中有特殊字符(空格,括号,引号,[]!$&*;|\),那么直接输入空格会造成系统识别困难,必须使用特殊的语法来表示这些字符。例如上例中,空格前添加反斜杠“\”(back slash)即可:cd Punlic/Drop\ Box/。除了反斜杠,也可以用引号的方法:cd "Public/Drop Box"。

——如果不想手动输入,也可以把文件从 Finder 拖到 Terminal 窗口来创建绝对路径,这会方便一些,因为上面提到的所有特殊字符在拖动后都会自动变成系统可识别的表示方法。其实,更有效率的解决方案是使用 Tab Complete 功能。

Tab Complete 是 command line 中最能给你节省时间的特性之一,利用它的自动完成文件、目录名称功能还可以防止你输入错误。使用cd进入你的 home folder,使用cd P命令,然后按下tab按键。你可能会听到错误音,因为你的 home folder 内有多个 P 开头的文件夹。再按一次tab,Terminal 将会为你列出 P 开头的两个文件夹:Public 和 Pictures。按U,再按tab,Terminal 则会自动为你补全Public/。Tab complete 同样会处理那些特殊字符。注意,这会在末尾保留/符号,大部分时候这没问题,但如果出错,移除多余的/试一试。

另外,鄂化符~(tilde)在command line 中可以代表当前用户的 home folder。例如~/Public/Drop\ Box/是合法的。

查看隐藏文件

为了简化工作,command line 和 Finder 都会隐藏许多文件和文件夹,这些内容通常是系统需要的。不借助第三方工具让 Finder 显示隐藏文件比较困难,但是在 command line 中却非常简单。首先,许多隐藏文件的隐藏是通过隐藏属性在 Finder 中隐藏的,而 command line 会忽略这些属性,所以这些文件会在 command line 中显示。另外,ls命令会隐藏文件名以.开头的文件,但是这些文件却可以被显示出来,方法是利用-a选项。例如:

michelle$ ls -la

我们还添加了-l选项,目的是控制输出格式。如果你注意输出内容的话,会发现还包括...两项,它们分别表示当前文件夹和父文件夹(如图)。如果你不想显示这两项,只需要把-a改成-A即可。

Terminal ls -la命令
Terminal ls -la命令

前往其他卷

在 command line 中,系统卷(也称为 root volume)是由开始的一个正斜杠表示的。然而也许听起来不可思议,在 command line 中其他卷看起来就在文件系统中一个叫做 Volumes 的文件夹中。下面的命令清晰地显示出这种逻辑关系:我从我的 home folder 出发,最终前往一个叫 Time Machine 的卷,该卷是外接在 Mac 上的。

bogon:~ renfei$ pwd
/Users/renfei
bogon:~ renfei$ cd /Volumes/
bogon:Volumes renfei$ pwd
/Volumes
bogon:Volumes renfei$ ls
Macintosh SSD      Time Machine
bogon:Volumes renfei$ cd Time\ Machine/
bogon:Time Machine renfei$ pwd
/Volumes/Time Machine

用Command-Line管理文件

检视文件

有许多基础命令用来定位、检视文件和文件夹,包括catlesswhichfile以及find。别忘了,你可以利用man命令来查阅每个命令的使用指南。

cat

cat是“concatenate”的意思,会按顺序读取文件并输出到 Terminal 窗口,语法为cat后接你需要查看的文件的路径。cat命令也可以用>>来增加文本文件的内容,例如命令cat ../textOne.txt >> textTwo.txt会把 textOne.txt 的内容添加到 textTwo.txt 的结尾。这个>>就属于上一篇提到的“Extras”。

less

这个命令更适合用来查看长文本文件,因为它会允许你查找文本。语法为 less后接文件路径,和cat一样。用less命令打开的文件其实和你查看命令使用指南的时候使用的是一个查看器,所以操作是相同的,同样可以使用(上箭头)或(下箭头)来上下移动文本,使用 来翻页,输入/和关键字来按照关键字搜索,按Q来退出使用指南页面。除此之外,按V键来使用vi文本编辑器。

which

这个命令会定位某个命令的文件路径。换言之,它会告诉你你执行某个具体命令的时候,在使用哪个文件。语法为which后接某个命令。如图:

终端 which 命令
终端 which 命令

file

这个命令会尝试根据文件的内容输出文件类型。如果一个文件缺失了扩展名,那么这个命令可能会非常有用。语法为file后接文件路径。如图,此例为一个 PNG 文件,还给出了它的尺寸、颜色数等信息。

终端 file命令
终端 file命令

find

这个命令用来根据搜索关键词定位文件路径。 find命令不使用 Spotlight 搜索服务,但是它允许你设置非常具体的搜索条件,以及通配符(稍后介绍)。语法为find后接搜索的起始路径,后接定义搜索的选项,后接搜索内容(包含在引号里)。例如:

Terminal Find 命令
Terminal Find 命令

注意

  1. 如果你要搜索根目录,也许你想使用-x选项来避免搜索 /Volumes 文件夹。
  2. 如果想使用 Soptlight 搜索服务,使用mdfind命令后接搜索关键词即可。

使用通配符(Wildcard Characters)

下面是常用的通配符:

  • 星号(*,Asterisk)——代表任何长度的任何字符。例如*.tiff代表所有格式为tiff的文件。
  • 问号(?,Question mark)——代表任何单个字符。例如b?ok匹配 book 但是不匹配 brook。
  • 方括号([],Square brackets)——定义一定范围的字符,例如[Dd]ocument匹配 Document 以及 document;doc[1-9]匹配doc1, doc2, …, doc9。

配合使用上面三种通配符可以大大提高效率。

使用递归命令

简单来说,递归命令可以允许命令不执行于一个特定文件,而是指定的路径下的所有文件。大多数命令包含一个-r或者-R选项,来设定你想递归地执行这个命令。例如下面的例子,展示了添加-Rls命令的执行方式:

Terminal -R选项
Terminal -R选项

编辑文件和文件夹

有许多基础的命令用来编辑文件和文件夹,包括mkdircpmvrmrmdir以及vi。下面我们来简要地介绍一下这些命令。

mkdir

“make diretory”的缩写,用来创建文件夹,语法为mkdir后接新文件夹的目录。可以用-p选项,来一起创建路径中不存在的文件夹(这样你就不用挨层创建了)。

cp

“copy”的缩写,用来把文件从一处复制到另一处。语法为cp后接原始路径,后接目标路径。如果你想复制整个文件夹和所有内容,需要添加-R选项。如果指定的目标路径不含文件名,则 cp 命令会按原名复制。如果指定的目标路径包括文件名,则会复制为你指定的文件名。如果仅指定新文件名,则会在原处以新名称创建文件副本。注意,系统会自动替换同名文件而不出现提示。

mv

“move”的缩写,用来移动文件。语法为mv后接原路径,后接新路径。mv 的指定路径规则和 cp 是一样的(没错,如果仅指定新文件名,它就成了重命名命令)。

rm

“remove”的缩写,会永久删除文件。注意,command-line中没有废纸篓。语法为rm后接文件路径。然而,使用 rm 命令删除的文件有可能可以通过数据恢复工具恢复。如果希望安全删除文件,可以使用srm命令。

rmdir和rm -R

rmdir是“remove directory”的缩写,这个命令会永久删除文件夹。再强调一遍,CLI 中木有废纸篓。语法为rmdir后接希望删除目录的路径。然而,rmdir 命令无法删除含有任何其他文件的文件夹,所以大多数情形下rmdir命令是不适用的。不过,你可以利用rm添加-R选项来删除文件夹及包含的所有文件。

vi

代表“visual”(视觉的),然而这个名称相当具有讽刺意味:vi可能是可视化效果最差的文本编辑器了。然而,vi 是 command line 中最常见的文本编辑器。用vi打开文本文件,只需要输入vi后接文件路径即可。Mac OS X 还提供了nano,一个更加现代的文本编辑器。它也更加方便,例如在底部包含了一个作弊小条(=_=),上面有常用的快捷键列表(你就不用背下来它们了)。然而,vi却有时是默认的文本编辑器,所以掌握vi是很有用的。

less命令类似,vi命令会占用整个 Terminal 空间来显示文件内容。打开后,在“command模式”,vi 会等你输入一些预定义字符来告诉 vi 你想做什么。你也可以使用键盘上的箭头键单纯地浏览文件。你想编辑时,按A开始(会进入编辑模式)。文字会插入到光标处。如果你想保存,需要先退出编辑模式进入 command 模式。方法是按下esc键。回到 command 模式后,按住shift同时按两次Z来保存并退出。如果你不想保存,在 command 模式输入:quit!并按enter
return
直接退出。

用Command-Line管理系统

使用su来切换用户

su命令代表“substitute user identity”,允许你在命令行中轻松切换到另一个用户账户。语法为su后接用户的短名称。然后会要求你输入密码(但是输入的时候不会显示)。执行完毕后,命令的前缀会改变,表示你拥有其他用户的权利。你可以利用who -m命令来验证当前登陆的身份。切换后,你会一直保持该用户身份,直至退出 Terminal 或者输入exit命令。

关于sudo的使用

sudo概述

更强大的命令就是sudo,代表“substitute user do”,或者,更恰当地,“super user do”。用sudo执行一个命令会使用 root 账户权限。当然,使用之前需要 administrator 账户(管理员账户)的授权(如输入密码)。

默认情况下,任何管理员账户都可以使用sudo来获取 root 权限,甚至当 root 账户在图形界面被禁用的情况下,sudo依然有效。这个命令是很多情况下我们不得不使用 Terminal 的原因,——同样也是给每个用户管理员身份的危险所在。不过,你可以调整sudo的配置文件,来限制它的使用。

bogon:~ renfei$ cat secret.txt
cat: secret.txt: Permission denied
bogon:~ renfei$ sudo cat secret.txt
Password:
This is the contents of the secret.txt text file that the user account renfei does not normally have access permissions to read. However, because he is an administrative user, she can use the sudo command to envoke root user access and read the contents of this file.

提示:如果由于你忘了使用sudo而导致命令行返回一个错误,只需输入sudo !!就可以用sudo来执行上一条指令。

记住,权力越大责任越大。不恰当地使用sudo可以轻易破坏你的系统设置。命令行只会在你第一次执行严重破坏性行为之前提示你,之后,它就会假设你清楚自己正在干什么。如果你只掌握三条使用命令行的准则,那将是:总是仔细检查你的命令;总是使用Tab completion来帮助你避免拼写错误;使用sudo之前,总是仔仔细细检查你的命令。

使用 sudo 切换 Shell

如果你是一个管理员用户,你需要执行很多条需要 root 权限的命令,你可以临时切换整个命令行 shell 来取得 root 级别的访问权限。方法就是先输入sudo -s,回车后再键入你的密码。

其他Command-Line技巧提示

  • 输入命令open .可以用 Finder 打开当前的位置。
  • 在 Terminal 的偏好里面可以设定它的外观和风格。
  • 中止一个错误的或者发疯的命令,可以使用组合键control + C
  • 你可以在执行前编辑命令,只需要使用箭头和键盘上的其他字母。
  • 没有输入任何命令时,你可以用来浏览历史命令。同样可以编辑和再次执行。
  • 你也可以使用history命令查看历史记录。
  • 你可以使用组合键control + L清屏。